<?php
session_start();
require_once __DIR__ . '/db/config.php';

if (!isset($_SESSION['user_id']) || !isset($_SESSION['company_id'])) {
    header('Location: /login.php');
    exit;
}

$company_id = $_SESSION['company_id'];
$employee_id = $_GET['id'] ?? null;
$error_message = '';
$success_message = '';

if (!$employee_id) {
    header('Location: /employees.php');
    exit;
}

// Fetch employee data
$stmt = db()->prepare("SELECT e.*, u.email FROM employees e JOIN users u ON e.user_id = u.id WHERE e.id = ? AND e.company_id = ?");
$stmt->execute([$employee_id, $company_id]);
$employee = $stmt->fetch();

if (!$employee) {
    header('Location: /employees.php');
    exit;
}

// Handle Update Employee
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_employee'])) {
    $first_name = $_POST['first_name'] ?? '';
    $last_name = $_POST['last_name'] ?? '';
    $position = $_POST['position'] ?? '';
    $basic_salary = $_POST['basic_salary'] ?? 0;

    if (empty($first_name) || empty($last_name) || empty($position) || empty($basic_salary)) {
        $error_message = 'All fields are required.';
    } else {
        try {
            $stmt = db()->prepare(
                "UPDATE employees SET first_name = ?, last_name = ?, position = ?, basic_salary = ? WHERE id = ? AND company_id = ?"
            );
            $stmt->execute([$first_name, $last_name, $position, $basic_salary, $employee_id, $company_id]);
            $success_message = 'Employee updated successfully!';
            
            // Refresh employee data after update
            $stmt = db()->prepare("SELECT * FROM employees WHERE id = ? AND company_id = ?");
            $stmt->execute([$employee_id, $company_id]);
            $employee = $stmt->fetch();

        } catch (Exception $e) {
            $error_message = "Failed to update employee: " . $e->getMessage();
        }
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Employee - GPTPayroll</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 font-sans leading-normal tracking-normal">
    <div class="flex md:flex-row-reverse flex-wrap">

        <!-- Main Content -->
        <div class="w-full md:w-4/5 bg-gray-100">
            <div class="container bg-gray-100 pt-16 px-6 mx-auto">

                <!-- Messages -->
                <?php if ($error_message): ?>
                    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                        <span class="block sm:inline"><?= htmlspecialchars($error_message) ?></span>
                    </div>
                <?php endif; ?>
                <?php if ($success_message): ?>
                    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
                        <span class="block sm:inline"><?= htmlspecialchars($success_message) ?></span>
                    </div>
                <?php endif; ?>

                <!-- Edit Employee Form -->
                <div class="bg-white shadow-md rounded p-8 mb-8">
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">Edit Employee</h2>
                    <form action="/edit_employee.php?id=<?= htmlspecialchars($employee_id) ?>" method="POST">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label for="first_name" class="block text-gray-700 text-sm font-bold mb-2">First Name</label>
                                <input type="text" name="first_name" id="first_name" value="<?= htmlspecialchars($employee['first_name']) ?>" required class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700">
                            </div>
                            <div>
                                <label for="last_name" class="block text-gray-700 text-sm font-bold mb-2">Last Name</label>
                                <input type="text" name="last_name" id="last_name" value="<?= htmlspecialchars($employee['last_name']) ?>" required class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700">
                            </div>
                            <div>
                                <label for="email" class="block text-gray-700 text-sm font-bold mb-2">Email</label>
                                <input type="email" name="email" id="email" value="<?= htmlspecialchars($employee['email'] ?? '') ?>" readonly disabled class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 bg-gray-200">
                                <p class="text-xs text-gray-500 mt-1">Email cannot be changed.</p>
                            </div>
                            <div>
                                <label for="position" class="block text-gray-700 text-sm font-bold mb-2">Position</label>
                                <input type="text" name="position" id="position" value="<?= htmlspecialchars($employee['position']) ?>" required class="shadow appearance-none border rounded w-full py-.2 px-3 text-gray-700">
                            </div>
                             <div>
                                <label for="basic_salary" class="block text-gray-700 text-sm font-bold mb-2">Basic Salary (ZMW)</label>
                                <input type="number" step="0.01" name="basic_salary" id="basic_salary" value="<?= htmlspecialchars($employee['basic_salary']) ?>" required class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700">
                            </div>
                        </div>
                        <div class="mt-6">
                            <button type="submit" name="update_employee" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">
                                Update Employee
                            </button>
                            <a href="/employees.php" class="inline-block align-baseline font-bold text-sm text-blue-500 hover:text-blue-800 ml-4">
                                Cancel
                            </a>
                        </div>
                    </form>
                </div>

            </div>
        </div>

        <!-- Sidebar -->
        <div class="w-full md:w-1/5 bg-gray-800 md:min-h-screen">
            <div class="md:relative mx-auto lg:float-right lg:px-6">
                <ul class="list-reset flex flex-row md:flex-col text-center md:text-left">
                    <li class="mr-3 flex-1">
                        <a href="/dashboard.php" class="block py-4 px-4 text-gray-400 hover:text-white no-underline">Dashboard</a>
                    </li>
                    <li class="mr-3 flex-1">
                        <a href="/employees.php" class="block py-4 px-4 text-white font-bold no-underline">Employees</a>
                    </li>
                    <li class="mr-3 flex-1">
                        <a href="/payroll.php" class="block py-4 px-4 text-gray-400 hover:text-white no-underline">Payroll</a>
                    </li>
                    <li class="mr-3 flex-1">
                        <a href="/payroll_history.php" class="block py-4 px-4 text-gray-400 hover:text-white no-underline">Payroll History</a>
                    </li>
                    <li class="mr-3 flex-1">
                        <a href="/settings.php" class="block py-4 px-4 text-gray-400 hover:text-white no-underline">Settings</a>
                    </li>
                    <li class="mr-3 flex-1">
                        <a href="/logout.php" class="block py-4 px-4 text-gray-400 hover:text-white no-underline">Logout</a>
                    </li>
                </ul>
            </div>
        </div>

    </div>
</body>
</html>