<?php
// app/model/api/employee.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once __DIR__ . '/../service/EmployeeService.php';

$service = new EmployeeService();

$action = isset($_GET['action']) ? $_GET['action'] : '';
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            if ($action === 'search') {
                $searchData = [
                    'nom' => isset($_GET['nom']) ? $_GET['nom'] : '',
                    'prenom' => isset($_GET['prenom']) ? $_GET['prenom'] : '',
                    'cin' => isset($_GET['cin']) ? $_GET['cin'] : '',
                    'email' => isset($_GET['email']) ? $_GET['email'] : '',
                    'login' => isset($_GET['login']) ? $_GET['login'] : '',
                    'specialite' => isset($_GET['specialite']) ? $_GET['specialite'] : '',
                    'status' => isset($_GET['status']) ? $_GET['status'] : '',
                    'grade_id' => isset($_GET['grade_id']) ? $_GET['grade_id'] : '',
                    'echellon_id' => isset($_GET['echellon_id']) ? $_GET['echellon_id'] : ''
                ];
                $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                $perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;

                $result = $service->search($searchData, $page, $perPage);
                echo json_encode(['success' => true, 'data' => $result]);
            } elseif ($action === 'get' && isset($_GET['id'])) {
                $data = $service->getEmployee($_GET['id']);
                if ($data) {
                    echo json_encode(['success' => true, 'data' => $data]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Employé non trouvé']);
                }
            } elseif ($action === 'stats') {
                $data = $service->getStats();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'all') {
                $data = $service->getAllEmployees();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'export') {
                $csv = $service->exportToCsv();
                if ($csv) {
                    header('Content-Type: text/csv; charset=utf-8');
                    header('Content-Disposition: attachment; filename="employes_' . date('Y-m-d') . '.csv"');
                    echo $csv;
                    exit();
                } else {
                    echo json_encode(['success' => false, 'message' => 'Aucun employé à exporter']);
                }
            } else {
                $data = $service->findAll('nom ASC');
                echo json_encode(['success' => true, 'data' => $data]);
            }
            break;

        case 'POST':
            if ($action === 'login') {
                $input = json_decode(file_get_contents('php://input'), true);
                $email = $input['email'] ?? '';
                $password = $input['password'] ?? '';

                if (empty($email) || empty($password)) {
                    echo json_encode(['success' => false, 'message' => 'Email et mot de passe requis']);
                    break;
                }

                $result = $service->login($email, $password);

                if ($result['success'] && isset($result['data'])) {
                    session_start();
                    $_SESSION['employee'] = $result['data'];
                    $_SESSION['employee_id'] = $result['data']['id'];
                }

                echo json_encode($result);
            } else {
                $input = json_decode(file_get_contents('php://input'), true);
                if ($input) {
                    $id = $service->createEmployee($input);
                    echo json_encode(['success' => true, 'id' => $id, 'message' => 'Employé créé avec succès']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Données invalides']);
                }
            }
            break;

        case 'PUT':
            if (isset($_GET['id'])) {
                $input = json_decode(file_get_contents('php://input'), true);
                if ($input) {
                    // Vérifier si c'est une mise à jour de mot de passe uniquement
                    if ($action === 'update_password' && isset($input['password'])) {
                        $service->updatePassword($_GET['id'], $input['password']);
                        echo json_encode(['success' => true, 'message' => 'Mot de passe mis à jour avec succès']);
                    } else {
                        $service->updateEmployee($_GET['id'], $input);
                        echo json_encode(['success' => true, 'message' => 'Employé mis à jour avec succès']);
                    }
                } else {
                    echo json_encode(['success' => false, 'message' => 'Données invalides']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'ID requis']);
            }
            break;

        case 'DELETE':
            if (isset($_GET['id'])) {
                $service->deleteEmployee($_GET['id']);
                echo json_encode(['success' => true, 'message' => 'Employé supprimé avec succès']);
            } else {
                echo json_encode(['success' => false, 'message' => 'ID requis']);
            }
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Méthode non autorisée']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>