<?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');

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

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

$service = new CandidatService();

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

try {
    switch ($method) {
        case 'GET':
            if ($action === 'search') {
                // Search with filters
                $searchData = [
                    'nom' => isset($_GET['nom']) ? $_GET['nom'] : '',
                    'prenom' => isset($_GET['prenom']) ? $_GET['prenom'] : '',
                    'email' => isset($_GET['email']) ? $_GET['email'] : '',
                    'cin' => isset($_GET['cin']) ? $_GET['cin'] : '',
                    'phone' => isset($_GET['phone']) ? $_GET['phone'] : ''
                ];
                $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'])) {
                // Get single candidat
                $data = $service->getCandidat($_GET['id']);
                if ($data) {
                    echo json_encode(['success' => true, 'data' => $data]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Candidat not found']);
                }
            } elseif ($action === 'check_inscriptions' && isset($_GET['candidat_id'])) {
                $candidatId = $_GET['candidat_id'];
                $result = $service->checkCandidatInscriptions($candidatId);
                print_r($result);
                echo json_encode(['success' => true, 'data' => $result]);
            } else {
                // Get all candidats
                $data = $service->findAll('id DESC');
                echo json_encode(['success' => true, 'data' => $data]);
            }
            break;

        case 'POST':
            // Create new candidat
            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 login successful, store candidat data in PHP session
                if ($result['success'] && isset($result['data'])) {
                    session_start();
                    $_SESSION['candidat'] = $result['data'];
                    $_SESSION['candidat_id'] = $result['data']['id'];
                }

                echo json_encode($result);

            } else if ($action === 'forgot_password') {
                    $input = json_decode(file_get_contents('php://input'), true);
                    $email = trim($input['email'] ?? '');

                    if (empty($email)) {
                        echo json_encode(['success' => false, 'message' => 'Le email est obligatoire.']);
                        break;
                    }

                    $result = $service->forgotPassword($email);
                    echo json_encode($result);
                    break;
                } else {
                    $input = json_decode(file_get_contents('php://input'), true);
                    if ($input) {
                        $result = $service->createCandidat($input);
                        echo json_encode($result);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Invalid input data']);
                    }
                }
            break;

        case 'PUT':
            if (isset($_GET['id'])) {
                $input = json_decode(file_get_contents('php://input'), true);

                if ($action === 'update_password') {
                    $result = $service->updateCandidatWithPassword($_GET['id'], $input);
                    echo json_encode($result);
                } else {
                    $result = $service->updateCandidatWithPassword($_GET['id'], $input);
                    echo json_encode($result);
                }
            }
            break;

        case 'DELETE':
            // Delete candidat
            if (isset($_GET['id'])) {
                $service->deleteCandidat($_GET['id']);
                echo json_encode(['success' => true, 'message' => 'Candidat deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'ID required']);
            }
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
