<?php
session_start();
include 'config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// --- 1. Get and validate emp_id, month, year ---
$emp_id = intval($_GET['emp_id'] ?? 0);
$selected_month = intval($_GET['month'] ?? date('m'));
$selected_year = intval($_GET['year'] ?? date('Y'));

// Validate month and year
if ($selected_month < 1 || $selected_month > 12) $selected_month = date('m');
if ($selected_year < 2000 || $selected_year > 2100) $selected_year = date('Y');

// --- 2. If no valid emp_id → redirect to selection ---
if ($emp_id <= 0) {
    // Preserve month/year in redirect
    $redirect = "select_employee.php?month=$selected_month&year=$selected_year";
    header("Location: $redirect");
    exit();
}

// --- 3. Securely fetch employee ---
$stmt = $conn->prepare("SELECT first_name, last_name, basic_salary FROM users WHERE id = ?");
$stmt->bind_param("i", $emp_id);
$stmt->execute();
$res = $stmt->get_result();
$emp = $res->fetch_assoc();

if (!$emp) {
    // Show friendly message + redirect
    $_SESSION['error'] = "Employee not found. Please select a valid employee.";
    $redirect = "select_employee.php?month=$selected_month&year=$selected_year";
    header("Location: $redirect");
    exit();
}
$stmt->close();

// --- 4. Process form submission ---
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $employee_name = $emp['first_name'] . ' ' . $emp['last_name'];
    $basic_salary = floatval($_POST['basic_salary'] ?? 0);
    $hra = floatval($_POST['hra'] ?? 0);
    $other_allowance = floatval($_POST['other_allowance'] ?? 0);
    $it = floatval($_POST['it'] ?? 0);
    $pt = floatval($_POST['pt'] ?? 0);
    $pf = floatval($_POST['pf'] ?? 0);
    $vpf = floatval($_POST['vpf'] ?? 0);
    $esi = floatval($_POST['esi'] ?? 0);
    $loan_principal = floatval($_POST['loan_principal'] ?? 0);
    $loan_interest = floatval($_POST['loan_interest'] ?? 0);
    $salary_advance = floatval($_POST['salary_advance'] ?? 0);
    $late_hours = intval($_POST['late_hours'] ?? 0);
    $unpaid_leave = intval($_POST['unpaid_leave'] ?? 0);
    $other_deductions = floatval($_POST['other_deductions'] ?? 0);
    $office_working_days = intval($_POST['office_working_days'] ?? 0);
    $no_of_absent = intval($_POST['no_of_absent'] ?? 0);
    $no_of_present = intval($_POST['no_of_present'] ?? 0);
    $unpaid_leave_difference = intval($_POST['unpaid_leave_difference'] ?? 0);
    $status = 'draft';
    $approved_by = $_SESSION['user_id'];

    // Calculate totals
    $total_gross_salary = $basic_salary + $hra + $other_allowance;
    $total_deductions = $it + $pt + $pf + $vpf + $esi + $loan_principal + $loan_interest + $salary_advance + $other_deductions;
    $net_earnings = $total_gross_salary - $total_deductions;

    // --- 5. Secure INSERT ---
    $query = "INSERT INTO payroll_records (
        employee_name, month, employee_id, year, basic_salary, hra, other_allowance, 
        total_gross_salary, it, pt, pf, vpf, esi, loan_principal, loan_interest, 
        salary_advance, late_hours, unpaid_leave, other_deductions, total_deductions, 
        net_earnings, office_working_days, no_of_absent, no_of_present, unpaid_leave_difference, 
        status, approved_by
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = mysqli_prepare($conn, $query);
    if (!$stmt) {
        die("Prepare failed: " . mysqli_error($conn));
    }

    mysqli_stmt_bind_param(
        $stmt, 
        "siiiddddddddddddiiididiiiss",
        $employee_name, $selected_month, $emp_id, $selected_year, $basic_salary, $hra, $other_allowance,
        $total_gross_salary, $it, $pt, $pf, $vpf, $esi, $loan_principal, $loan_interest,
        $salary_advance, $late_hours, $unpaid_leave, $other_deductions, $total_deductions,
        $net_earnings, $office_working_days, $no_of_absent, $no_of_present, $unpaid_leave_difference,
        $status, $approved_by
    );

    if (!mysqli_stmt_execute($stmt)) {
        $message = '<div class="alert alert-danger">Error saving payroll: ' . mysqli_stmt_error($stmt) . '</div>';
    } else {
        $message = '<div class="alert alert-success text-center">
            Payroll processed for <strong>' . htmlspecialchars($employee_name) . '</strong> for 
            <strong>' . date('F Y', mktime(0, 0, 0, $selected_month, 1, $selected_year)) . '</strong><br>
            Net Earnings: <strong>₹' . number_format($net_earnings, 2) . '</strong>
        </div>';
    }
    mysqli_stmt_close($stmt);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Process Payroll</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
            display: flex;
            min-height: 100vh;
        }
        .sidebar {
            width: 250px;
            background: #2c3e50;
            color: #fff;
            padding: 15px;
            transition: transform 0.3s ease;
            position: fixed;
            top: 0;
            bottom: 0;
            z-index: 1000;
            transform: translateX(-250px);
        }
        .sidebar.active { transform: translateX(0); }
        .sidebar h2 { font-size: 1rem; margin-bottom: 15px; }
        .sidebar a { color: #fff; text-decoration: none; padding: 8px 10px; display: block; border-radius: 4px; margin-bottom: 5px; font-size: 0.9rem; }
        .sidebar a:hover, .sidebar a.active { background: #1abc9c; }
        .hamburger {
            position: fixed; top: 10px; left: 10px; z-index: 1100;
            background: #2c3e50; color: #fff; border: none; padding: 8px;
            border-radius: 4px; cursor: pointer;
        }
        .content { flex: 1; padding: 15px; margin-left: 0; transition: margin-left 0.3s ease; }
        .content.active { margin-left: 250px; }
        h1 { font-size: 1.5rem; margin-bottom: 15px; color: #333; }
        h2 { font-size: 1.2rem; color: #2c3e50; margin: 20px 0 15px; }
        .form-control[readonly] { background-color: #e9ecef; }
        .btn-back { margin-bottom: 1rem; }
        .card { background: white; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 1.5rem; }
        @media (max-width: 576px) {
            .row > div { margin-bottom: 0.5rem; }
            h1 { font-size: 1.2rem; }
            h2 { font-size: 1rem; }
        }
    </style>
</head>
<body>
    <!-- Hamburger -->
    <button class="hamburger" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <h2>Mypeopleconnect</h2>
        <a href="dashboard_admin.php"><i class="fas fa-home"></i> Organisation Chart</a>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"><i class="fas fa-home"></i> DAP</a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="manage_users.php">Employee Details</a></li>
                <li><a class="dropdown-item" href="manage_documents.php">Policies Rolled Out</a></li>
                <li><a class="dropdown-item" href="digital.php">Acceptance Confirmed</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"><i class="fas fa-users"></i> CAB</a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="payroll_dashboard.php">Payroll</a></li>
                <li><a class="dropdown-item" href="leave_dashboard.php">Leave</a></li>
                <li><a class="dropdown-item" href="grievance_dashboard.php">Grievance Portal</a></li>
            </ul>
        </div>
        <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <!-- Main Content -->
    <div class="content" id="content">
        <h1 class="text-primary text-center">Process Payroll</h1>

        <!-- Success/Error Message -->
        <?php if ($message): ?>
            <?= $message ?>
        <?php endif; ?>

        <!-- Flash Error from Redirect -->
        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger text-center w-75 mx-auto">
                <?= $_SESSION['error'] ?>
            </div>
            <?php unset($_SESSION['error']); ?>
        <?php endif; ?>

        <div class="w-75 mx-auto">
            <div class="card">
                <div class="btn-back p-3 border-bottom">
                    <a href="payroll_dashboard.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back
                    </a>
                    <a href="select_employee.php?month=<?= $selected_month ?>&year=<?= $selected_year ?>" 
                       class="btn btn-info ms-2">
                        <i class="fas fa-users"></i> Change Employee
                    </a>
                </div>

                <form method="post" class="p-3">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Employee</label>
                            <input type="text" class="form-control" value="<?= htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']) ?>" readonly>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold">Month</label>
                            <input type="text" class="form-control" value="<?= date('F', mktime(0, 0, 0, $selected_month, 1)) ?>" readonly>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold">Year</label>
                            <input type="text" class="form-control" value="<?= $selected_year ?>" readonly>
                        </div>
                    </div>

                    <h2 class="mt-4 text-primary">Earnings</h2>
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">Basic Salary (₹)</label>
                            <input type="number" step="0.01" name="basic_salary" class="form-control" 
                                   value="<?= htmlspecialchars($emp['basic_salary']) ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">HRA (₹)</label>
                            <input type="number" step="0.01" name="hra" class="form-control" value="0.00">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Other Allowance (₹)</label>
                            <input type="number" step="0.01" name="other_allowance" class="form-control" value="0.00">
                        </div>
                    </div>

                    <h2 class="mt-4 text-danger">Deductions</h2>
                    <div class="row g-3">
                        <?php 
                        $deductions = [
                            'it' => 'Income Tax', 'pt' => 'Professional Tax', 'pf' => 'Provident Fund',
                            'vpf' => 'Voluntary PF', 'esi' => 'ESI', 'loan_principal' => 'Loan Principal',
                            'loan_interest' => 'Loan Interest', 'salary_advance' => 'Salary Advance',
                            'other_deductions' => 'Other Deductions'
                        ];
                        foreach ($deductions as $key => $label): ?>
                        <div class="col-md-3">
                            <label class="form-label"><?= $label ?> (₹)</label>
                            <input type="number" step="0.01" name="<?= $key ?>" class="form-control" value="0.00">
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <h2 class="mt-4 text-info">Attendance</h2>
                    <div class="row g-3">
                        <?php 
                        $attendance = [
                            'office_working_days' => 'Office Working Days',
                            'no_of_absent' => 'No. of Absent Days',
                            'no_of_present' => 'No. of Present Days',
                            'unpaid_leave_difference' => 'Unpaid Leave Difference',
                            'late_hours' => 'Late Hours',
                            'unpaid_leave' => 'Unpaid Leave Days'
                        ];
                        foreach ($attendance as $key => $label): ?>
                        <div class="col-md-3">
                            <label class="form-label"><?= $label ?></label>
                            <input type="number" name="<?= $key ?>" class="form-control" value="0">
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="text-center mt-4">
                        <button type="submit" class="btn btn-success btn-lg px-5">
                            <i class="fas fa-save"></i> Process Payroll
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('content').classList.toggle('active');
        }
    </script>
</body>
</html>