<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/helpers.php';

check_role('administrador');

$user = get_logged_in_user();

$job_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$updated = isset($_GET['updated']) && $_GET['updated'] == '1';

// Handle status update
$update_error = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['application_id']) && isset($_POST['status'])) {
    $application_id = isset($_POST['application_id']) ? (int)$_POST['application_id'] : 0;
    $status = isset($_POST['status']) ? $_POST['status'] : '';
    $job_id_from_form = isset($_POST['job_id']) ? (int)$_POST['job_id'] : 0;

    // Debug logging
    error_log("POST received - application_id: $application_id, status: $status, job_id: $job_id_from_form");
    error_log("Raw POST data: " . print_r($_POST, true));

    // Validate required fields
    if (empty($application_id) || $application_id <= 0) {
        error_log("Invalid or missing application_id: $application_id");
        $update_error = 'ID de aplicación inválido o faltante.';
    } elseif (empty($status)) {
        error_log("Missing status");
        $update_error = 'Estado faltante.';
    } else {
        // Check if application exists before attempting update
        $check_stmt = $pdo->prepare("SELECT id, status, job_id FROM applications WHERE id = ?");
        $check_stmt->execute([$application_id]);
        $existing_app = $check_stmt->fetch();

        if (!$existing_app) {
            error_log("Application $application_id does not exist in database");
            // Let's also check what applications do exist
            $all_apps_stmt = $pdo->query("SELECT id FROM applications LIMIT 10");
            $all_apps = $all_apps_stmt->fetchAll(PDO::FETCH_COLUMN);
            error_log("Existing application IDs: " . implode(', ', $all_apps));
            $update_error = 'La aplicación especificada no existe en la base de datos.';
        } else {
            error_log("Application $application_id exists with current status: " . $existing_app['status'] . ", job_id: " . $existing_app['job_id']);

        if (in_array($status, ['pending', 'reviewed', 'accepted', 'rejected'])) {
        try {
            error_log("Executing update query for application $application_id with status $status");

            $stmt = $pdo->prepare("UPDATE applications SET status = ? WHERE id = ?");
            $result = $stmt->execute([$status, $application_id]);

            error_log("Query executed, result: " . ($result ? 'true' : 'false'));
            error_log("Rows affected: " . $stmt->rowCount());

            if ($result && $stmt->rowCount() > 0) {
                error_log("Status update successful for application $application_id");
                header('Location: /bolsa2/admin/job-applications.php' . ($job_id_from_form ? '?id=' . $job_id_from_form . '&updated=1' : '?updated=1'));
                exit;
            } else {
                error_log("Status update failed for application $application_id - no rows affected or query failed");
                $update_error = 'Error al actualizar el estado. Verifique que la aplicación existe.';
            }
        } catch (Exception $e) {
            error_log("Exception during status update: " . $e->getMessage());
            $update_error = 'Error interno: ' . $e->getMessage();
        }
            } else {
                error_log("Invalid status: $status");
                $update_error = 'Estado inválido.';
            }
        }
    }
} else {
    error_log("POST not received or missing required fields");
}

$page_title = $job_id ? 'Postulantes a Oferta de Trabajo' : 'Todas las Postulaciones';

$per_page = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);
$offset = ($page - 1) * $per_page;
// $search = isset($_GET['search']) ? trim($_GET['search']) : '';
$search = '';

// Get job info if specific job
$job_info = null;
if ($job_id) {
    $stmt = $pdo->prepare("SELECT j.*, c.company_name FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.id = ? AND j.deleted_at IS NULL");
    $stmt->execute([$job_id]);
    $job_info = $stmt->fetch();
    if (!$job_info) {
        header('Location: jobs.php');
        exit;
    }
}

// Get total count
$count_query = "SELECT COUNT(*) as total FROM applications a
                LEFT JOIN students s ON a.applicant_id = s.id AND a.applicant_type = 'student'
                LEFT JOIN graduates g ON a.applicant_id = g.id AND a.applicant_type = 'graduate'
                JOIN users u ON (s.user_id = u.id OR g.user_id = u.id)
                JOIN jobs j ON a.job_id = j.id
                JOIN companies c ON j.company_id = c.id";

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

if ($job_id) {
    $where_conditions[] = "a.job_id = ?";
    $params[] = $job_id;
}

if ($search) {
    $where_conditions[] = "(u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR j.title LIKE ? OR c.company_name LIKE ?)";
    $params = array_merge($params, ["%$search%", "%$search%", "%$search%", "%$search%", "%$search%"]);
}

if (!empty($where_conditions)) {
    $count_query .= " WHERE " . implode(" AND ", $where_conditions);
}

$total_stmt = $pdo->prepare($count_query);
$total_stmt->execute($params);
$total_applications = $total_stmt->fetch()['total'];
$total_pages = ceil($total_applications / $per_page);

$content = ($updated ? '<div class="alert alert-success">Estado de la solicitud actualizado con éxito.</div>' : '') .
           ($update_error ? '<div class="alert alert-danger">' . htmlspecialchars($update_error) . '</div>' : '') . '
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">' . ($job_id ? 'Postulantes: ' . htmlspecialchars($job_info['title']) : 'Todas las Postulaciones') . '</h3>
                <div class="card-tools">
                    <span class="badge bg-info">' . $total_applications . ' Total</span>
                    ' . ($job_id ? '<a href="' . url('admin/jobs.php') . '" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i> Volver a Ofertas</a>' : '') . '
                </div>
            </div>';

if ($job_id) {
    $content .= '<div class="card-header bg-light">
                    <div class="row">
                        <div class="col-md-6 mb-3 mb-md-0">
                            <strong>Empresa:</strong> ' . htmlspecialchars($job_info['company_name']) . '<br>
                            <strong>Oferta:</strong> ' . htmlspecialchars($job_info['title']) . '<br>
                            <strong>Estado:</strong> <span class="badge ' . ($job_info['status'] == 'active' ? 'bg-success' : 'bg-secondary') . '">' . ucfirst($job_info['status']) . '</span>
                        </div>
                        <div class="col-md-6">
                            <strong>Salario:</strong> ' . ($job_info['salary'] ? 'S/. ' . number_format($job_info['salary'], 2) : 'No especificado') . '<br>
                            <strong>Ubicación:</strong> ' . htmlspecialchars($job_info['location'] ?: 'No especificada') . '<br>
                            <strong>Fecha de publicación:</strong> ' . date('d/m/Y', strtotime($job_info['posted_date'])) . '
                        </div>
                    </div>
                </div>';
}

$content .= '
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Postulante</th>
                            ' . (!$job_id ? '<th>Oferta de Trabajo</th><th>Empresa</th>' : '') . '
                            <th>Fecha de Postulación</th>
                            <th>Estado</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>';

$query = "SELECT a.id, a.status, a.applied_date, a.notes, a.applicant_type,
                 u.id as user_id, u.first_name, u.last_name, u.email,
                 j.title as job_title, j.id as job_id,
                 c.company_name,
                 s.id as student_id,
                 g.id as graduate_id
          FROM applications a
          LEFT JOIN students s ON a.applicant_id = s.id AND a.applicant_type = 'student'
          LEFT JOIN graduates g ON a.applicant_id = g.id AND a.applicant_type = 'graduate'
          JOIN users u ON (s.user_id = u.id OR g.user_id = u.id)
          JOIN jobs j ON a.job_id = j.id
          JOIN companies c ON j.company_id = c.id";

if (!empty($where_conditions)) {
    $query .= " WHERE " . implode(" AND ", $where_conditions);
}

$query .= " ORDER BY a.applied_date DESC LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;

$stmt = $pdo->prepare($query);
$stmt->execute($params);

while ($row = $stmt->fetch()) {
    $status_badge = '';
    switch ($row['status']) {
        case 'pending':
            $status_badge = '<span class="badge bg-warning">Pendiente</span>';
            break;
        case 'reviewed':
            $status_badge = '<span class="badge bg-info">Revisado</span>';
            break;
        case 'accepted':
            $status_badge = '<span class="badge bg-success">Aceptado</span>';
            break;
        case 'rejected':
            $status_badge = '<span class="badge bg-danger">Rechazado</span>';
            break;
    }

    $applicant_name = htmlspecialchars($row['first_name'] . ' ' . $row['last_name']);
    $applicant_type_label = $row['applicant_type'] == 'graduate' ? ' (Egresado)' : ' (Estudiante)';

    $content .= '<tr>
        <td>' . $row['id'] . '</td>
        <td>
            <strong>' . $applicant_name . '</strong>' . $applicant_type_label . '<br>
            <small class="text-muted">' . htmlspecialchars($row['email']) . '</small>
        </td>
        ' . (!$job_id ? '<td><a href="view-job.php?id=' . $row['job_id'] . '">' . htmlspecialchars($row['job_title']) . '</a></td>
        <td>' . htmlspecialchars($row['company_name']) . '</td>' : '') . '
        <td>' . date('d/m/Y H:i', strtotime($row['applied_date'])) . '</td>
        <td>' . $status_badge . '</td>
        <td>
            <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#statusModal" data-application-id="' . $row['id'] . '" data-job-id="' . $row['job_id'] . '" data-current-status="' . $row['status'] . '" data-applicant-name="' . htmlspecialchars($applicant_name) . '" data-applicant-type="' . $row['applicant_type'] . '">
                <i class="fas fa-edit"></i> Cambiar Estado
            </button>
            <a href="' . url('admin/resume.php?id=' . $row['user_id']) . '" class="btn btn-secondary btn-sm">
                <i class="fas fa-user"></i> Ver Detalles
            </a>
        </td>
    </tr>';
}

$content .= '</tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>';

// Status Update Modal
$content .= '
<div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="statusModalLabel">Cambiar Estado de Postulación - Estado actual: <span id="modal_title_status" class="badge"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" action="" id="statusForm">
                <div class="modal-body">
                    <input type="hidden" name="application_id" id="application_id">
                    <input type="hidden" name="job_id" id="modal_job_id" value="' . $job_id . '">
                    <p><strong>Postulante:</strong> <span id="applicant_name"></span></p>
                    <p><strong>Estado actual:</strong> <span id="current_status_display" class="badge"></span></p>
                    <div class="mb-3">
                        <label for="status" class="form-label">Nuevo Estado:</label>
                        <select name="status" id="status" class="form-select" required>
                            <option value="">Seleccionar estado...</option>
                            <option value="pending">Pendiente</option>
                            <option value="reviewed">Revisado</option>
                            <option value="accepted">Aceptado</option>
                            <option value="rejected">Rechazado</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Actualizar Estado</button>
                </div>
            </form>
        </div>
    </div>
</div>';

// Pagination
if ($total_pages > 1) {
    $content .= '<div class="row">
        <div class="col-12">
            <nav aria-label="Applications pagination">
                <ul class="pagination justify-content-center">';

    // Previous button
    if ($page > 1) {
        $search_param = $search ? '&search=' . urlencode($search) : '';
        $id_param = $job_id ? '&id=' . $job_id : '';
        $content .= '<li class="page-item"><a class="page-link" href="?page=' . ($page - 1) . $id_param . $search_param . '">Previous</a></li>';
    } else {
        $content .= '<li class="page-item disabled"><span class="page-link">Previous</span></li>';
    }

    // Page numbers
    $start_page = max(1, $page - 2);
    $end_page = min($total_pages, $page + 2);

    if ($start_page > 1) {
        $search_param = $search ? '&search=' . urlencode($search) : '';
        $id_param = $job_id ? '&id=' . $job_id : '';
        $content .= '<li class="page-item"><a class="page-link" href="?page=1' . $id_param . $search_param . '">1</a></li>';
        if ($start_page > 2) {
            $content .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }

    for ($i = $start_page; $i <= $end_page; $i++) {
        $search_param = $search ? '&search=' . urlencode($search) : '';
        $id_param = $job_id ? '&id=' . $job_id : '';
        if ($i == $page) {
            $content .= '<li class="page-item active"><span class="page-link">' . $i . '</span></li>';
        } else {
            $content .= '<li class="page-item"><a class="page-link" href="?page=' . $i . $id_param . $search_param . '">' . $i . '</a></li>';
        }
    }

    if ($end_page < $total_pages) {
        $search_param = $search ? '&search=' . urlencode($search) : '';
        $id_param = $job_id ? '&id=' . $job_id : '';
        if ($end_page < $total_pages - 1) {
            $content .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
        $content .= '<li class="page-item"><a class="page-link" href="?page=' . $total_pages . $id_param . $search_param . '">' . $total_pages . '</a></li>';
    }

    // Next button
    if ($page < $total_pages) {
        $search_param = $search ? '&search=' . urlencode($search) : '';
        $id_param = $job_id ? '&id=' . $job_id : '';
        $content .= '<li class="page-item"><a class="page-link" href="?page=' . ($page + 1) . $id_param . $search_param . '">Next</a></li>';
    } else {
        $content .= '<li class="page-item disabled"><span class="page-link">Next</span></li>';
    }

    $content .= '</ul>
            </nav>
        </div>
    </div>';
}

$content .= '<script src="/bolsa2/assets/js/job-applications.js"></script>';

include '../includes/layout.php';