<?php
// ot_process.php
session_start();
include 'config.php';
if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['admin','superadmin'])) { header("Location: index.php"); exit; }

$selected_month = isset($_GET['month']) ? $_GET['month'] : date('Y-m');
$year = intval(date('Y', strtotime($selected_month . '-01')));
$month = intval(date('n', strtotime($selected_month . '-01')));

// Aggregate OT per emp_id for the month
$sql = "SELECT emp_id, COALESCE(SUM(ot_salary),0) AS ot_sum FROM ot WHERE DATE_FORMAT(ot_date, '%Y-%m') = ? GROUP BY emp_id";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $selected_month);
$stmt->execute();
$res = $stmt->get_result();

$updated = 0;
while ($r = $res->fetch_assoc()) {
    $emp_id = $r['emp_id'];
    $ot_sum = floatval($r['ot_sum']);

    // Upsert into salary table (emp_id, year, month)
    $check = $conn->prepare("SELECT id FROM salary WHERE emp_id = ? AND year = ? AND month = ? LIMIT 1");
    $check->bind_param("sii", $emp_id, $year, $month);
    $check->execute();
    $g = $check->get_result();

    if ($g && $g->num_rows) {
        // update ot_amount and gross/net (basic calculation handled in payroll, but we'll update ot_amount here)
        $row = $g->fetch_assoc();
        $upd = $conn->prepare("UPDATE salary SET ot_amount = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
        $upd->bind_param("di", $ot_sum, $row['id']);
        $upd->execute();
        $upd->close();
    } else {
        // insert minimal salary row with ot_amount (other amounts will be computed by payroll.php)
        $ins = $conn->prepare("INSERT INTO salary (emp_id, year, month, ot_amount, created_at) VALUES (?, ?, ?, ?, NOW())");
        $ins->bind_param("siii", $emp_id, $year, $month, $ot_sum); // NOTE: bind param types - emp_id string, year int, month int, ot_sum int? adjust below
        // Correction: ot_sum is decimal -> bind as double. Rebind properly:
        $ins->close();
        $ins = $conn->prepare("INSERT INTO salary (emp_id, year, month, ot_amount, created_at) VALUES (?, ?, ?, ?, NOW())");
        $ins->bind_param("siid", $emp_id, $year, $month, $ot_sum);
        $ins->execute();
        $ins->close();
    }
    $check->close();
    $updated++;
}

echo "<p>Processed OT for {$selected_month}. Updated {$updated} employees.</p>";
echo "<p><a href='attendance.php?month=" . urlencode($selected_month) . "'>Back to Attendance</a> | <a href='payroll.php?month=" . urlencode($selected_month) . "'>Run Payroll</a></p>";
