<?php

// Get month and year from URL parameters or use current month
$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 = 29375.00;

// Fetch daily production summary data (FG difference)
$production_sql = "
    SELECT 
        DAY(record_date) as day,
        DATE_FORMAT(record_date, '%d-%b') as date_display,
        DAYNAME(record_date) as day_name,
        fg_difference
    FROM daily_production_summary
    WHERE MONTH(record_date) = $month AND YEAR(record_date) = $year
    ORDER BY record_date ASC
";

$production_result = mysqli_query($conn, $production_sql);
$production_data = [];

while ($row = mysqli_fetch_assoc($production_result)) {
    $production_data[$row['day']] = $row;
}

// Fetch sales data (from production_planning)
$sales_sql = "
    SELECT 
        DAY(pp.req_date) as day,
        SUM(pp.req_qty * IFNULL(im.standard_cost_ebq, 0)) AS total_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)
    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']] = $row['total_sales'];
}

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

// Month name
$month_name = date('F Y', strtotime("$year-$month-01"));
?>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            max-width: 1400px;
            margin: 0 auto;
        }
        h2 {
            color: #333;
            margin-bottom: 20px;
            text-align: center;
            font-size: 24px;
            font-weight: bold;
        }
        .month-selector {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 5px;
        }
        .month-selector label {
            margin-right: 10px;
            font-weight: bold;
        }
        .month-selector select {
            padding: 5px 10px;
            margin-right: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .month-selector button {
            padding: 6px 15px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .month-selector button:hover {
            background-color: #0056b3;
        }
        .table-responsive {
            overflow-x: auto;
            margin-top: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 900px;
        }
        th, td {
            border: 1px solid #333;
            padding: 8px;
            text-align: center;
            font-size: 13px;
        }
        th {
            background-color: #4CAF50;
            color: white;
            font-weight: bold;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .weekend {
            background-color: #e0e0e0;
        }
        .no-data {
            color: #999;
            background-color: #f5f5f5;
        }
        .positive-variance {
            background-color: #c8e6c9;
            color: #2e7d32;
            font-weight: bold;
        }
        .negative-variance {
            background-color: #ffcdd2;
            color: #c62828;
            font-weight: bold;
        }
        .date-col {
            text-align: left;
            font-weight: 500;
        }
        .day-col {
            text-align: left;
        }
        .currency {
            text-align: right;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>TPL PRODUCTION TOTAL</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>
                        <th rowspan="2">Actual vs<br>target</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, ['Friday', 'Saturday', 'Sunday']);
                        //$row_class = $is_weekend ? 'weekend' : '';
                        
                        // Get production data
                        $prod = isset($production_data[$day]) ? $production_data[$day] : null;
                        $fg_difference = $prod ? floatval($prod['fg_difference']) : 0;
                        
                        // Get sales data
                        $sales = isset($sales_data[$day]) ? floatval($sales_data[$day]) : 0;
                        
                        // Calculate daily actual (sales + FG difference)
                        $daily_actual = $sales + $fg_difference;
                        
                        // 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;
                        
                        // Calculate variance
                        $variance = $cumv_actual - $cumv_target;
                        $variance_class = $variance >= 0 ? 'positive-variance' : 'negative-variance';
                    ?>
                        <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 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>
                            <td class="currency <?php echo $variance_class; ?>">
                                £ <?php echo number_format($variance, 2); ?>
                            </td>
                        </tr>
                    <?php endfor; ?>
                </tbody>
            </table>
        </div>
        
        <div style="margin-top: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 5px;">
            <h3 style="margin-top: 0;">Summary for <?php echo $month_name; ?></h3>
            <p><strong>Total Target:</strong> £<?php echo number_format($cumv_target, 2); ?></p>
            <p><strong>Total Actual:</strong> £<?php echo number_format($cumv_actual, 2); ?></p>
            <p><strong>Total Variance:</strong> 
                <span class="<?php echo ($cumv_actual - $cumv_target >= 0) ? 'positive-variance' : 'negative-variance'; ?>" style="padding: 5px 10px; border-radius: 3px;">
                    £<?php echo number_format($cumv_actual - $cumv_target, 2); ?>
                </span>
            </p>
            <p><strong>Achievement Rate:</strong> <?php echo $cumv_target > 0 ? number_format(($cumv_actual / $cumv_target) * 100, 2) : '0.00'; ?>%</p>
        </div>
    </div>
