<?php
// employee-management.php

ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

require_once("../config/config.php"); // $conn = mysqli connection

$success = $error = "";
$search = trim($_GET['search'] ?? '');

// Handle Delete (Soft Delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_employee'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $error = "Invalid request.";
    } else {
        $emp_id = $_POST['employee_id'] ?? '';
        $stmt = $conn->prepare("UPDATE employee_master SET status = 'inactive' WHERE employee_id = ? AND status = 'active'");
        $stmt->bind_param("s", $emp_id);
        if ($stmt->execute() && $stmt->affected_rows > 0) {
            $success = "Employee <strong>$emp_id</strong> has been removed.";
        } else {
            $error = "Employee not found or already removed.";
        }
        $stmt->close();
    }
}

// Fetch Employees
$sql = "SELECT 
            employee_id, full_name, mobile_number, designation, education, 
            date_of_joining, place_of_work, wages, decided_salary
        FROM employee_master 
        WHERE status = 'active'";

$params = [];
$types = '';
if ($search !== '') {
    $sql .= " AND (employee_id LIKE ? OR full_name LIKE ? OR mobile_number LIKE ? OR designation LIKE ?)";
    $like = "%$search%";
    $params = [$like, $like, $like, $like];
    $types = 'ssss';
}

$sql .= " ORDER BY id DESC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Management</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root { --primary: #8b5cf6; --primary-light: #a78bfa; --text: #e0e7ff; --success: #34d399; --error: #f87171; }
        * { margin:0; padding:0; box-sizing:border-box; }
        body { font-family:'Segoe UI',sans-serif; min-height:100vh; background:linear-gradient(rgba(0,0,0,0.6),rgba(0,0,0,0.6)),url('../background.jpeg') center/cover no-repeat fixed; color:var(--text); padding:20px; }
        .container { max-width:1400px; margin:0 auto; background:rgba(255,255,255,0.1); backdrop-filter:blur(16px); border-radius:24px; border:1px solid rgba(255,255,255,0.2); box-shadow:0 20px 50px rgba(0,0,0,0.4); overflow:hidden; }
        .header { background:rgba(255,255,255,0.15); padding:40px; text-align:center; position:relative; }
        .header h1 { font-size:2.5rem; margin-bottom:10px; }
        .add-btn { position:absolute; top:30px; right:40px; padding:14px 24px; background:linear-gradient(135deg,var(--primary),var(--primary-light)); border:none; border-radius:14px; color:white; font-weight:600; cursor:pointer; box-shadow:0 8px 20px rgba(139,92,246,0.4); transition:.3s; }
        .add-btn:hover { transform:translateY(-4px); box-shadow:0 12px 30px rgba(139,92,246,0.5); }
        .controls { padding:30px; display:flex; gap:20px; flex-wrap:wrap; align-items:center; }
        .search-box { flex:1; min-width:250px; position:relative; }
        .search-box input { width:100%; padding:16px 50px 16px 20px; background:rgba(255,255,255,0.15); border:1px solid rgba(255,255,255,0.3); border-radius:14px; color:white; font-size:16px; }
        .search-box i { position:absolute; right:18px; top:50%; transform:translateY(-50%); color:rgba(255,255,255,0.7); }
        .table-area { padding:0 30px 40px; overflow-x:auto; }
        table { width:100%; border-collapse:collapse; margin-top:20px; }
        th, td { padding:18px; text-align:left; border-bottom:1px solid rgba(255,255,255,0.15); }
        th { background:rgba(139,92,246,0.3); font-weight:600; font-size:1.05rem; }
        tr:hover { background:rgba(255,255,255,0.08); }
        .actions { display:flex; gap:12px; }
        .btn { padding:8px 14px; border:none; border-radius:8px; cursor:pointer; font-size:0.9rem; transition:.3s; }
        .btn-view { background:rgba(59,130,246,0.3); color:#93c5fd; }
        .btn-view:hover { background:rgba(59,130,246,0.5); }
        .btn-edit { background:rgba(34,197,94,0.3); color:#86efac; }
        .btn-edit:hover { background:rgba(34,197,94,0.5); }
        .btn-delete { background:rgba(239,68,68,0.3); color:#fca5a5; }
        .btn-delete:hover { background:rgba(239,68,68,0.5); }
        .message { padding:16px 20px; border-radius:14px; margin:20px 30px; display:flex; align-items:center; gap:12px; font-weight:600; backdrop-filter:blur(8px); }
        .success { background:rgba(52,211,153,0.2); border:1px solid rgba(74,222,128,0.4); }
        .error { background:rgba(239,68,68,0.2); border:1px solid rgba(252,165,165,0.4); }
        .no-results { text-align:center; padding:60px; font-size:1.2rem; opacity:0.8; }
        @media (max-width:992px) { .controls { flex-direction:column; align-items:stretch; } .add-btn { position:static; width:100%; margin-top:10px; } }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Employee Management</h1>
            <p>View and manage all registered employees</p>
            <a href="add_employee.php" class="add-btn">
                <i class="fas fa-user-plus"></i> Add New Employee
            </a>
        </div>

        <div class="controls">
            <div class="search-box">
                <form method="get">
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search by ID, Name, Mobile or Designation...">
                    <i class="fas fa-search"></i>
                </form>
            </div>
        </div>

        <?php if ($success): ?>
            <div class="message success"><i class="fas fa-check-circle"></i> <?= $success ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="message error"><i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <div class="table-area">
            <?php if ($result->num_rows > 0): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Employee ID</th>
                            <th>Full Name</th>
                            <th>Mobile</th>
                            <th>Designation</th>
                            <th>Education</th>
                            <th>Joining Date</th>
                            <th>Place of Work</th>
                            <th>Wages/Hr</th>
                            <th>Salary</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = $result->fetch_assoc()): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($row['employee_id']) ?></strong></td>
                                <td><?= htmlspecialchars($row['full_name']) ?></td>
                                <td><?= htmlspecialchars($row['mobile_number']) ?></td>
                                <td><?= htmlspecialchars($row['designation']) ?></td>
                                <td><?= htmlspecialchars($row['education']) ?></td>
                                <td><?= date('d-m-Y', strtotime($row['date_of_joining'])) ?></td>
                                <td><?= htmlspecialchars($row['place_of_work'] ?: '-') ?></td>
                                <td>₹<?= number_format($row['wages'], 2) ?></td>
                                <td>₹<?= number_format($row['decided_salary'], 2) ?></td>
                                <td class="actions">
                                    <a href="view-employee.php?id=<?= htmlspecialchars($row['employee_id']) ?>" class="btn btn-view" title="View">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="edit-employee.php?id=<?= htmlspecialchars($row['employee_id']) ?>" class="btn btn-edit" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <form method="post" style="display:inline;" onsubmit="return confirm('Are you sure you want to remove this employee?');">
                                        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                        <input type="hidden" name="employee_id" value="<?= htmlspecialchars($row['employee_id']) ?>">
                                        <button type="submit" name="delete_employee" class="btn btn-delete" title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="no-results">
                    <i class="fas fa-users" style="font-size:4rem; opacity:0.3; margin-bottom:20px;"></i>
                    <p>No employees found. <?= $search ? 'Try a different search term.' : 'Start by adding your first employee.' ?></p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>