<?php

$month = isset($_GET['month']) ? intval($_GET['month']) : date('n');
$year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');

// Validate month
if ($month < 1 || $month > 12) {
    $month = date('n');
}

// Get number of days in the month
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);

// Daily target (you can make this dynamic from database)
$daily_target = 27500.00;

// Fetch sales data (from production_planning) - ONLY SOURCE OF DATA
$sales_sql = "
    SELECT 
        DAY(pp.req_date) as day,
        DATE_FORMAT(pp.req_date, '%d-%b') as date_display,
        DAYNAME(pp.req_date) as day_name,
        SUM(pp.req_qty * IFNULL(im.standard_cost_ebq, 0)) AS daily_sales
    FROM production_planning pp
    LEFT JOIN item_management im ON im.id = pp.part_id
    WHERE MONTH(pp.req_date) = $month AND YEAR(pp.req_date) = $year
    GROUP BY DAY(pp.req_date), DATE_FORMAT(pp.req_date, '%d-%b'), DAYNAME(pp.req_date)
    ORDER BY pp.req_date ASC
";

$sales_result = mysqli_query($conn, $sales_sql);
$sales_data = [];

while ($row = mysqli_fetch_assoc($sales_result)) {
    $sales_data[$row['day']] = [
        'date_display' => $row['date_display'],
        'day_name' => $row['day_name'],
        'daily_sales' => floatval($row['daily_sales'])
    ];
}

// Calculate cumulative values
$cumv_target = 0;
$cumv_actual = 0;

// Month name
$month_name = date('F Y', strtotime("$year-$month-01"));
?>
<style>

.container {
    background-color: white;
    padding: 20px;
    border-radius: 0; /* remove rounded corners for full width */
    box-shadow: none; /* remove shadow */
    
    /* FULL SCREEN WIDTH */
    width: 100%;
    max-width: 100%;
    min-height: 100vh;
    margin: 0;
}

h2 {
    color: #333;
    margin-bottom: 20px;
    text-align: center;
    font-size: 28px;
    font-weight: bold;
}

.table-responsive {
    overflow-x: auto;
    margin-top: 20px;
}

table {
    width: 100%;
    border-collapse: collapse;

    /* Make the table fully stretch */
    min-width: 100%;
}

th, td {
    border: 1px solid #333;
    padding: 10px;
    text-align: center;
    font-size: 14px;
}

th {
    background-color: #4CAF50;
    color: white;
    font-weight: bold;
    position: sticky;
    top: 0;
    z-index: 10;
}

.weekend {
    background-color: #e0e0e0;
}

.no-data {
    color: #999;
    background-color: #f5f5f5;
}

.summary {
    margin-top: 20px;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 5px;
}

.summary h3 {
    margin-top: 0;
    color: #333;
}
</style>
    <div class="container">
        <h2>TPL SALES</h2>
        
        <div class="month-selector">
            <form method="GET" action="">
                <label for="month">Month:</label>
                <select name="month" id="month">
                    <?php for ($m = 1; $m <= 12; $m++): ?>
                        <option value="<?php echo $m; ?>" <?php echo ($m == $month) ? 'selected' : ''; ?>>
                            <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                        </option>
                    <?php endfor; ?>
                </select>
                
                <label for="year">Year:</label>
                <select name="year" id="year">
                    <?php for ($y = date('Y') - 2; $y <= date('Y') + 1; $y++): ?>
                        <option value="<?php echo $y; ?>" <?php echo ($y == $year) ? 'selected' : ''; ?>>
                            <?php echo $y; ?>
                        </option>
                    <?php endfor; ?>
                </select>
                
                <button type="submit">View Report</button>
            </form>
        </div>

        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th rowspan="2">Date</th>
                        <th rowspan="2">Day</th>
                        <th colspan="2">TARGET</th>
                        <th colspan="2">ACTUAL</th>
                    </tr>
                    <tr>
                        <th>DAILY TARGET</th>
                        <th>CUMV TARGET</th>
                        <th>DAILY ACTUAL</th>
                        <th>CUMV ACTUAL</th>
                    </tr>
                </thead>
                <tbody>
                    <?php for ($day = 1; $day <= $days_in_month; $day++): 
                        // Get date info
                        $date = "$year-$month-$day";
                        $timestamp = strtotime($date);
                        $day_name = date('l', $timestamp);
                        $date_display = sprintf('%02d-%s', $day, date('M', $timestamp));
                        
                        // Check if weekend
                        $is_weekend = in_array($day_name, ['Saturday', 'Sunday']);
                        
                        // Get sales data
                        $sales_info = isset($sales_data[$day]) ? $sales_data[$day] : null;
                        $daily_actual = $sales_info ? $sales_info['daily_sales'] : 0;
                        
                        // Daily target (0 for weekends)
                        $daily_target_value = $is_weekend ? 0 : $daily_target;
                        
                        // Update cumulative values
                        $cumv_target += $daily_target_value;
                        $cumv_actual += $daily_actual;
                        
                        // Row styling
                        $row_class = $is_weekend ? 'weekend' : '';
                        
                        // Check if cumv target overflows (represented by ######### in your image)
                       
                    ?>
                        <tr class="<?php echo $row_class; ?>">
                            <td class="date-col"><?php echo $date_display; ?></td>
                            <td class="day-col"><?php echo $day_name; ?></td>
                            <td class="currency">
                                <?php 
                                if ($daily_target_value > 0) {
                                    echo '£' . number_format($daily_target_value, 2);
                                } else {
                                    echo '<span class="no-data">-</span>';
                                }
                                ?>
                            </td>
                            <td class="currency <?php echo $show_overflow ? 'cumv-overflow' : ''; ?>">
                                <?php 
                                if ($show_overflow) {
                                    echo '##########';
                                } else {
                                    echo '£ ' . number_format($cumv_target, 2);
                                }
                                ?>
                            </td>
                            <td class="currency">
                                <?php 
                                if ($daily_actual > 0) {
                                    echo '£ ' . number_format($daily_actual, 2);
                                } else {
                                    echo '<span class="no-data">-</span>';
                                }
                                ?>
                            </td>
                            <td class="currency">£ <?php echo number_format($cumv_actual, 2); ?></td>
                        </tr>
                    <?php endfor; ?>
                </tbody>
            </table>
        </div>
        
        <div class="summary">
            <h3>Summary for <?php echo $month_name; ?></h3>
            <p><strong>Total Target:</strong> £<?php echo number_format($cumv_target, 2); ?></p>
            <p><strong>Total Actual Sales:</strong> £<?php echo number_format($cumv_actual, 2); ?></p>
            <p><strong>Variance:</strong> £<?php echo number_format($cumv_actual - $cumv_target, 2); ?></p>
            <p><strong>Achievement Rate:</strong> <?php echo $cumv_target > 0 ? number_format(($cumv_actual / $cumv_target) * 100, 2) : '0.00'; ?>%</p>
        </div>
    </div>
