<?php
require_once '../config/config.php';
requireLogin('admin');

$database = new Database();
$db = $database->getConnection();

$success = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_employee'])) {
        $employee_code = strtoupper(sanitize($_POST['employee_code']));
        $employee_name = sanitize($_POST['employee_name']);
        $department = sanitize($_POST['department']);
        $position = sanitize($_POST['position']);
        $manager_name = sanitize($_POST['manager_name']);
        $manager_email = sanitize($_POST['manager_email']);
        $hire_date = $_POST['hire_date'];
        
        if (empty($employee_code) || empty($employee_name)) {
            $error = 'Employee code and name are required.';
        } else {
            try {
                $stmt = $db->prepare("
                    INSERT INTO employee_codes (employee_code, employee_name, department, position, manager_name, manager_email, hire_date) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([$employee_code, $employee_name, $department, $position, $manager_name, $manager_email, $hire_date]);
                $success = 'Employee code added successfully.';
            } catch (PDOException $e) {
                if ($e->getCode() == 23000) {
                    $error = 'Employee code already exists.';
                } else {
                    $error = 'Error adding employee code. Please try again.';
                }
            }
        }
    } elseif (isset($_POST['update_status'])) {
        $employee_id = (int)$_POST['employee_id'];
        $status = $_POST['status'];
        
        if (in_array($status, ['active', 'inactive'])) {
            try {
                $stmt = $db->prepare("UPDATE employee_codes SET status = ? WHERE id = ?");
                $stmt->execute([$status, $employee_id]);
                $success = 'Employee status updated successfully.';
            } catch (PDOException $e) {
                $error = 'Error updating employee status.';
            }
        }
    } elseif (isset($_POST['delete_employee'])) {
        $employee_id = (int)$_POST['employee_id'];
        
        try {
            $stmt = $db->prepare("DELETE FROM employee_codes WHERE id = ?");
            $stmt->execute([$employee_id]);
            $success = 'Employee code deleted successfully.';
        } catch (PDOException $e) {
            $error = 'Error deleting employee code. It may be in use by candidates.';
        }
    }
}

// Get employee codes with usage statistics
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? 'all';

$where_conditions = [];
$params = [];

if ($search) {
    $where_conditions[] = "(ec.employee_code LIKE ? OR ec.employee_name LIKE ? OR ec.department LIKE ?)";
    $search_param = "%$search%";
    $params = [$search_param, $search_param, $search_param];
}

if ($status_filter !== 'all') {
    $where_conditions[] = "ec.status = ?";
    $params[] = $status_filter;
}

$where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";

$stmt = $db->prepare("
    SELECT 
        ec.*,
        COUNT(c.id) as candidates_using
    FROM employee_codes ec 
    LEFT JOIN candidates c ON ec.employee_code = c.employee_code 
    $where_clause 
    GROUP BY ec.id 
    ORDER BY ec.created_at DESC
");
$stmt->execute($params);
$employee_codes = $stmt->fetchAll();

// Get statistics
$stmt = $db->prepare("
    SELECT 
        status,
        COUNT(*) as count 
    FROM employee_codes 
    GROUP BY status
");
$stmt->execute();
$stats_data = $stmt->fetchAll();

$stats = [
    'active' => 0,
    'inactive' => 0,
    'total' => 0
];

foreach ($stats_data as $stat) {
    $stats[$stat['status']] = $stat['count'];
    $stats['total'] += $stat['count'];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Codes - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="dashboard.php">Dashboard</a>
                <a class="nav-link" href="../auth/logout.php">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid py-4">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2">
                <div class="list-group">
                    <a href="dashboard.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-chart-bar me-2"></i>Dashboard
                    </a>
                    <a href="candidates.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-users me-2"></i>All Candidates
                    </a>
                    <a href="internal-candidates.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-building me-2"></i>Internal Candidates
                    </a>
                    <a href="employee-codes.php" class="list-group-item list-group-item-action active">
                        <i class="fas fa-id-card me-2"></i>Employee Codes
                    </a>
                    <a href="companies.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-building me-2"></i>Companies
                    </a>
                    <a href="jobs.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-briefcase me-2"></i>Jobs
                    </a>
                    <a href="applications.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-file-alt me-2"></i>Applications
                    </a>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1 class="h3">Employee Codes Management</h1>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addEmployeeModal">
                        <i class="fas fa-plus me-2"></i>Add Employee Code
                    </button>
                </div>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="card text-white bg-primary">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="card-title"><?php echo $stats['total']; ?></h4>
                                        <p class="card-text">Total Employees</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-users fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card text-white bg-success">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="card-title"><?php echo $stats['active']; ?></h4>
                                        <p class="card-text">Active</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-check fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card text-white bg-secondary">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="card-title"><?php echo $stats['inactive']; ?></h4>
                                        <p class="card-text">Inactive</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-pause fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Search and Filter -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <select name="status" class="form-select">
                                    <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>>All Status</option>
                                    <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <input type="text" name="search" class="form-control" placeholder="Search by employee code, name, or department" value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-search"></i> Search
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Employee Codes List -->
                <div class="card">
                    <div class="card-body">
                        <?php if (empty($employee_codes)): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-id-card fa-4x text-muted mb-3"></i>
                                <h5 class="text-muted">No employee codes found</h5>
                                <p class="text-muted">Add employee codes to allow internal candidate registration.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Employee Code</th>
                                            <th>Employee Name</th>
                                            <th>Department</th>
                                            <th>Position</th>
                                            <th>Manager</th>
                                            <th>Hire Date</th>
                                            <th>Status</th>
                                            <th>Used by Candidates</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($employee_codes as $employee): ?>
                                            <tr>
                                                <td>
                                                    <span class="badge bg-primary font-monospace"><?php echo htmlspecialchars($employee['employee_code']); ?></span>
                                                </td>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($employee['employee_name']); ?></strong>
                                                </td>
                                                <td><?php echo htmlspecialchars($employee['department'] ?? 'N/A'); ?></td>
                                                <td><?php echo htmlspecialchars($employee['position'] ?? 'N/A'); ?></td>
                                                <td>
                                                    <?php if ($employee['manager_name']): ?>
                                                        <div><?php echo htmlspecialchars($employee['manager_name']); ?></div>
                                                        <small class="text-muted"><?php echo htmlspecialchars($employee['manager_email']); ?></small>
                                                    <?php else: ?>
                                                        <span class="text-muted">N/A</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php echo $employee['hire_date'] ? formatDate($employee['hire_date']) : 'N/A'; ?>
                                                </td>
                                                <td>
                                                    <?php
                                                    $badge_class = $employee['status'] === 'active' ? 'bg-success' : 'bg-secondary';
                                                    ?>
                                                    <span class="badge <?php echo $badge_class; ?>">
                                                        <?php echo ucfirst($employee['status']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span class="badge bg-info"><?php echo $employee['candidates_using']; ?></span>
                                                </td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <button type="button" class="btn btn-outline-primary" 
                                                                onclick="editEmployee(<?php echo $employee['id']; ?>, '<?php echo htmlspecialchars($employee['employee_code']); ?>', '<?php echo htmlspecialchars($employee['employee_name']); ?>', '<?php echo htmlspecialchars($employee['department']); ?>', '<?php echo htmlspecialchars($employee['position']); ?>', '<?php echo htmlspecialchars($employee['manager_name']); ?>', '<?php echo htmlspecialchars($employee['manager_email']); ?>', '<?php echo $employee['hire_date']; ?>')">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                        <button type="button" class="btn btn-outline-<?php echo $employee['status'] === 'active' ? 'warning' : 'success'; ?>" 
                                                                onclick="toggleStatus(<?php echo $employee['id']; ?>, '<?php echo $employee['status'] === 'active' ? 'inactive' : 'active'; ?>', '<?php echo htmlspecialchars($employee['employee_name']); ?>')">
                                                            <i class="fas fa-<?php echo $employee['status'] === 'active' ? 'pause' : 'play'; ?>"></i>
                                                        </button>
                                                        <?php if ($employee['candidates_using'] == 0): ?>
                                                            <button type="button" class="btn btn-outline-danger" 
                                                                    onclick="deleteEmployee(<?php echo $employee['id']; ?>, '<?php echo htmlspecialchars($employee['employee_name']); ?>')">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Employee Modal -->
    <div class="modal fade" id="addEmployeeModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title">Add Employee Code</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="employee_code" class="form-label">Employee Code *</label>
                                <input type="text" class="form-control text-uppercase" id="employee_code" name="employee_code" required>
                                <div class="form-text">Will be converted to uppercase</div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="employee_name" class="form-label">Employee Name *</label>
                                <input type="text" class="form-control" id="employee_name" name="employee_name" required>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="department" class="form-label">Department</label>
                                <input type="text" class="form-control" id="department" name="department">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="position" class="form-label">Position</label>
                                <input type="text" class="form-control" id="position" name="position">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="manager_name" class="form-label">Manager Name</label>
                                <input type="text" class="form-control" id="manager_name" name="manager_name">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="manager_email" class="form-label">Manager Email</label>
                                <input type="email" class="form-control" id="manager_email" name="manager_email">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="hire_date" class="form-label">Hire Date</label>
                            <input type="date" class="form-control" id="hire_date" name="hire_date">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="add_employee" class="btn btn-primary">Add Employee Code</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Status Toggle Form (hidden) -->
    <form method="POST" id="statusForm" style="display: none;">
        <input type="hidden" name="employee_id" id="status_employee_id">
        <input type="hidden" name="status" id="status_value">
        <input type="hidden" name="update_status" value="1">
    </form>

    <!-- Delete Form (hidden) -->
    <form method="POST" id="deleteForm" style="display: none;">
        <input type="hidden" name="employee_id" id="delete_employee_id">
        <input type="hidden" name="delete_employee" value="1">
    </form>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleStatus(employeeId, newStatus, employeeName) {
            const action = newStatus === 'active' ? 'activate' : 'deactivate';
            if (confirm(`Are you sure you want to ${action} ${employeeName}?`)) {
                document.getElementById('status_employee_id').value = employeeId;
                document.getElementById('status_value').value = newStatus;
                document.getElementById('statusForm').submit();
            }
        }
        
        function deleteEmployee(employeeId, employeeName) {
            if (confirm(`Are you sure you want to delete employee code for ${employeeName}? This action cannot be undone.`)) {
                document.getElementById('delete_employee_id').value = employeeId;
                document.getElementById('deleteForm').submit();
            }
        }
        
        // Auto-uppercase employee code input
        document.getElementById('employee_code').addEventListener('input', function() {
            this.value = this.value.toUpperCase();
        });
    </script>
</body>
</html>