<?php
include 'db.php';

// Get settings (we assume only one row with id=1)
$settings = $conn->query("SELECT * FROM payroll_settings WHERE id=1")->fetch_assoc();
if (!$settings) {
    die("❌ Payroll settings not configured. Please set them up first.");
}

// Handle generation
if (isset($_POST['generate'])) {
    $month = $_POST['month']; // format: YYYY-MM

    // Get all employees
    $employees = $conn->query("SELECT * FROM employees");
    if ($employees->num_rows == 0) {
        die("❌ No employees found.");
    }

    $skipped = 0;
    $created = 0;

    while ($emp = $employees->fetch_assoc()) {
        $employee_id = $emp['id'];

        // ✅ Safeguard: check if payroll already exists
        $check = $conn->prepare("SELECT id FROM payrolls WHERE employee_id=? AND payroll_month=?");
        $check->bind_param("is", $employee_id, $month);
        $check->execute();
        $check->store_result();

        if ($check->num_rows > 0) {
            $skipped++;
            continue; // skip this employee
        }

        $basic       = $settings['default_basic'];
        $allowances  = $settings['default_allowance'];
        $ot          = 0.00;

        $gross = $basic + $allowances + $ot;

        // Calculate deductions
        $epf_emp   = $gross * ($settings['epf_employee_rate'] / 100);
        $socso_emp = $gross * ($settings['socso_employee_rate'] / 100);
        $sip_emp   = $gross * ($settings['sip_employee'] / 100);

        $total_deductions = $epf_emp + $socso_emp + $sip_emp;
        $net = $gross - $total_deductions;

        // Store deductions in JSON
        $deductions = json_encode([
            ['code' => 'EPF', 'amount' => $epf_emp],
            ['code' => 'SOCSO', 'amount' => $socso_emp],
            ['code' => 'SIP', 'amount' => $sip_emp],
        ]);

        // Insert payroll record
        $stmt = $conn->prepare("
            INSERT INTO payrolls 
            (employee_id, payroll_month, basic, allowances, ot, gross, deductions, total_deductions, net_pay, status) 
            VALUES (?,?,?,?,?,?,?,?,?,?)
        ");

        $status = "Pending";

        $stmt->bind_param(
            "isddddddds",
            $employee_id,
            $month,
            $basic,
            $allowances,
            $ot,
            $gross,
            $deductions,
            $total_deductions,
            $net,
            $status
        );
        $stmt->execute();

        // Insert log
        $payroll_id = $stmt->insert_id;
        $log = $conn->prepare("INSERT INTO payroll_logs (payroll_id, action, actor, details) VALUES (?, ?, ?, ?)");
        $action  = "generated";
        $actor   = "system";
        $details = "Payroll generated for {$emp['name']} ({$month})";
        $log->bind_param("isss", $payroll_id, $action, $actor, $details);
        $log->execute();

        $created++;
    }

    echo "<script>alert('✅ Payroll generated for {$month}\\nCreated: {$created}\\nSkipped (already exists): {$skipped}'); window.location='payroll_list.php?month={$month}';</script>";
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Generate Payroll</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container py-4">
    <h2 class="mb-4">🧾 Generate Payroll</h2>
    <form method="post" class="card p-4 shadow-sm">
        <div class="mb-3">
            <label class="form-label">Payroll Month</label>
            <input type="month" class="form-control" name="month" required>
        </div>
        <div class="d-flex justify-content-between">
            <a href="dashboard.php" class="btn btn-secondary">⬅ Back</a>
            <button type="submit" name="generate" class="btn btn-primary">⚡ Generate</button>
        </div>
    </form>
</body>
</html>
