<?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'];
$error_message = '';
$success_message = '';

// Handle Delete Employee
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_employee'])) {
    $employee_id = $_POST['employee_id'] ?? null;
    $user_id = $_POST['user_id'] ?? null;

    if ($employee_id && $user_id) {
        try {
            $pdo = db();
            $pdo->beginTransaction();

            // 1. Delete the employee record
            $stmt = $pdo->prepare("DELETE FROM employees WHERE id = ? AND company_id = ?");
            $stmt->execute([$employee_id, $company_id]);

            // 2. Delete the user record
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND company_id = ?");
            $stmt->execute([$user_id, $company_id]);

            $pdo->commit();
            $success_message = 'Employee deleted successfully!';
        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error_message = "Failed to delete employee: " . $e->getMessage();
        }
    } else {
        $error_message = 'Invalid employee data for deletion.';
    }
}

// Handle Add Employee
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_employee'])) {
    $first_name = $_POST['first_name'] ?? '';
    $last_name = $_POST['last_name'] ?? '';
    $email = $_POST['email'] ?? '';
    $position = $_POST['position'] ?? '';
    $basic_salary = $_POST['basic_salary'] ?? 0;
    $password = $_POST['password'] ?? 'password123'; // Default password, should be changed by user

    if (empty($first_name) || empty($last_name) || empty($email) || empty($position) || empty($basic_salary)) {
        $error_message = 'All fields are required to add an employee.';
    } else {
        try {
            $pdo = db();
            $pdo->beginTransaction();

            // Check if email exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                throw new Exception("A user with this email already exists.");
            }

            // 1. Create a user record for the employee
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (company_id, email, password, role) VALUES (?, ?, ?, 'employee')");
            $stmt->execute([$company_id, $email, $hashed_password]);
            $user_id = $pdo->lastInsertId();

            // 2. Create the employee record
            $stmt = $pdo->prepare(
                "INSERT INTO employees (user_id, company_id, first_name, last_name, position, basic_salary) VALUES (?, ?, ?, ?, ?, ?)"
            );
            $stmt->execute([$user_id, $company_id, $first_name, $last_name, $position, $basic_salary]);

            $pdo->commit();
            $success_message = 'Employee added successfully!';

        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error_message = "Failed to add employee: " . $e->getMessage();
        }
    }
}

// Fetch employees for the company
$stmt = db()->prepare("SELECT e.*, u.email FROM employees e JOIN users u ON e.user_id = u.id WHERE e.company_id = ? ORDER BY e.created_at DESC");
$stmt->execute([$company_id]);
$employees = $stmt->fetchAll();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Employees - 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; ?>

                <!-- Add Employee Form -->
                <div class="bg-white shadow-md rounded p-8 mb-8">
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">Add New Employee</h2>
                    <form action="/employees.php" 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" 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" 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" required class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700">
                            </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" 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" 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="add_employee" class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">
                                Add Employee
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Employee List -->
                <div class="bg-white shadow-md rounded p-8">
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">Employee Roster</h2>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Email</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Position</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Salary</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Hire Date</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php if (empty($employees)): ?>
                                    <tr>
                                        <td colspan="5" class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-center">No employees found.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($employees as $employee): ?>
                                        <tr>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?= htmlspecialchars($employee['first_name'] . ' ' . $employee['last_name']) ?></td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?= htmlspecialchars($employee['email']) ?></td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?= htmlspecialchars($employee['position']) ?></td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">ZMW <?= htmlspecialchars(number_format((float)$employee['basic_salary'], 2)) ?></td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?= htmlspecialchars(date('d M Y', strtotime($employee['hire_date'] ?? $employee['created_at']))) ?></td>
                                            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                                <a href="edit_employee.php?id=<?= $employee['id'] ?>" class="text-indigo-600 hover:text-indigo-900">Edit</a>
                                                <form action="/employees.php" method="POST" class="inline-block" onsubmit="return confirm('Are you sure you want to delete this employee?');">
                                                    <input type="hidden" name="employee_id" value="<?= $employee['id'] ?>">
                                                    <input type="hidden" name="user_id" value="<?= $employee['user_id'] ?>">
                                                    <button type="submit" name="delete_employee" class="text-red-600 hover:text-red-900 ml-4">Delete</button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </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>
