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

check_role('alumno');

$user = get_logged_in_user();

// Get student
$stmt = $pdo->prepare("SELECT * FROM students WHERE user_id = ?");
$stmt->execute([$user['id']]);
$student = $stmt->fetch();

if (!$student) {
    die('Student profile not found.');
}

// Get student's work experience
$stmt = $pdo->prepare("SELECT * FROM student_work_experience WHERE student_id = ? ORDER BY start_date DESC");
$stmt->execute([$student['id']]);
$work_experiences = $stmt->fetchAll();

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_experience'])) {
        $company_name = trim($_POST['company_name']);
        $job_title = trim($_POST['job_title']);
        $employment_type = $_POST['employment_type'];
        $location = trim($_POST['location']);
        $start_date = $_POST['start_date'];
        $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
        $current_job = isset($_POST['current_job']) ? 1 : 0;
        $salary_range = trim($_POST['salary_range']);

        if (empty($company_name) || empty($job_title) || empty($start_date)) {
            $error = 'Se requieren el nombre de la empresa, el puesto de trabajo y la fecha de inicio.';
        } else {
            // Handle certificate upload
            $certificate_path = '';
            if (isset($_FILES['certificate_file']) && $_FILES['certificate_file']['error'] == 0) {
                $allowed_types = ['application/pdf'];
                if (in_array($_FILES['certificate_file']['type'], $allowed_types) && $_FILES['certificate_file']['size'] <= 10485760) { // 10MB
                    $upload_dir = '../uploads/work_certificates/';
                    if (!is_dir($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }

                    $file_extension = pathinfo($_FILES['certificate_file']['name'], PATHINFO_EXTENSION);
                    $file_name = 'work_cert_' . $student['id'] . '_' . time() . '_' . uniqid() . '.' . $file_extension;
                    $file_path = $upload_dir . $file_name;

                    if (move_uploaded_file($_FILES['certificate_file']['tmp_name'], $file_path)) {
                        $certificate_path = 'uploads/work_certificates/' . $file_name;
                    } else {
                        $error = 'No se pudo cargar el archivo del certificado.';
                    }
                } else {
                    $error = 'Tipo de archivo no válido o archivo demasiado grande. Solo se permiten archivos PDF de menos de 10 MB.';
                }
            }

            if (!$error) {
                // If current job, set end_date to null
                if ($current_job) {
                    $end_date = null;
                }

                $stmt = $pdo->prepare("INSERT INTO student_work_experience (student_id, company_name, job_title, employment_type, location, start_date, end_date, current_job, salary_range, certificate_file) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                if ($stmt->execute([$student['id'], $company_name, $job_title, $employment_type, $location, $start_date, $end_date, $current_job, $salary_range, $certificate_path])) {
                    $success = 'Experiencia laboral agregada exitosamente.';
                    // Refresh work experiences list
                    $stmt = $pdo->prepare("SELECT * FROM student_work_experience WHERE student_id = ? ORDER BY start_date DESC");
                    $stmt->execute([$student['id']]);
                    $work_experiences = $stmt->fetchAll();
                } else {
                    $error = 'No se pudo agregar experiencia laboral.';
                }
            }
        }
    } elseif (isset($_POST['edit_experience'])) {
        $experience_id = $_POST['experience_id'];
        $company_name = trim($_POST['company_name']);
        $job_title = trim($_POST['job_title']);
        $employment_type = $_POST['employment_type'];
        $location = trim($_POST['location']);
        $start_date = $_POST['start_date'];
        $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
        $current_job = isset($_POST['current_job']) ? 1 : 0;
        $salary_range = trim($_POST['salary_range']);

        if (empty($company_name) || empty($job_title) || empty($start_date)) {
            $error = 'Se requieren el nombre de la empresa, el puesto de trabajo y la fecha de inicio.';
        } else {
            // Handle certificate upload (optional for edit)
            $certificate_path = '';
            if (isset($_FILES['certificate_file']) && $_FILES['certificate_file']['error'] == 0) {
                $allowed_types = ['application/pdf'];
                if (in_array($_FILES['certificate_file']['type'], $allowed_types) && $_FILES['certificate_file']['size'] <= 10485760) { // 10MB
                    $upload_dir = '../uploads/work_certificates/';
                    if (!is_dir($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }

                    // Get old certificate to delete if exists
                    $stmt = $pdo->prepare("SELECT certificate_file FROM student_work_experience WHERE id = ? AND student_id = ?");
                    $stmt->execute([$experience_id, $student['id']]);
                    $old_exp = $stmt->fetch();
                    if ($old_exp && $old_exp['certificate_file'] && file_exists('../' . $old_exp['certificate_file'])) {
                        unlink('../' . $old_exp['certificate_file']);
                    }

                    $file_extension = pathinfo($_FILES['certificate_file']['name'], PATHINFO_EXTENSION);
                    $file_name = 'work_cert_' . $student['id'] . '_' . time() . '_' . uniqid() . '.' . $file_extension;
                    $file_path = $upload_dir . $file_name;

                    if (move_uploaded_file($_FILES['certificate_file']['tmp_name'], $file_path)) {
                        $certificate_path = 'uploads/work_certificates/' . $file_name;
                    } else {
                        $error = 'No se pudo cargar el archivo del certificado.';
                    }
                } else {
                    $error = 'Tipo de archivo no válido o archivo demasiado grande. Solo se permiten archivos PDF de menos de 10 MB.';
                }
            }

            if (!$error) {
                // If current job, set end_date to null
                if ($current_job) {
                    $end_date = null;
                }

                if ($certificate_path) {
                    $stmt = $pdo->prepare("UPDATE student_work_experience SET company_name = ?, job_title = ?, employment_type = ?, location = ?, start_date = ?, end_date = ?, current_job = ?, salary_range = ?, certificate_file = ? WHERE id = ? AND student_id = ?");
                    $params = [$company_name, $job_title, $employment_type, $location, $start_date, $end_date, $current_job, $salary_range, $certificate_path, $experience_id, $student['id']];
                } else {
                    $stmt = $pdo->prepare("UPDATE student_work_experience SET company_name = ?, job_title = ?, employment_type = ?, location = ?, start_date = ?, end_date = ?, current_job = ?, salary_range = ? WHERE id = ? AND student_id = ?");
                    $params = [$company_name, $job_title, $employment_type, $location, $start_date, $end_date, $current_job, $salary_range, $experience_id, $student['id']];
                }

                if ($stmt->execute($params)) {
                    $success = 'Experiencia laboral actualizada exitosamente.';
                    // Refresh work experiences list
                    $stmt = $pdo->prepare("SELECT * FROM student_work_experience WHERE student_id = ? ORDER BY start_date DESC");
                    $stmt->execute([$student['id']]);
                    $work_experiences = $stmt->fetchAll();
                } else {
                    $error = 'No se pudo actualizar la experiencia laboral.';
                }
            }
        }
    } elseif (isset($_POST['delete_experience'])) {
        $experience_id = $_POST['experience_id'];

        // Get certificate file path before deleting
        $stmt = $pdo->prepare("SELECT certificate_file FROM student_work_experience WHERE id = ? AND student_id = ?");
        $stmt->execute([$experience_id, $student['id']]);
        $exp = $stmt->fetch();

        if ($exp && $exp['certificate_file'] && file_exists('../' . $exp['certificate_file'])) {
            // Try to delete the file, but don't fail if permissions don't allow it
            @unlink('../' . $exp['certificate_file']);
        }

        $stmt = $pdo->prepare("DELETE FROM student_work_experience WHERE id = ? AND student_id = ?");
        if ($stmt->execute([$experience_id, $student['id']])) {
            $success = 'Experiencia laboral eliminada exitosamente.';
            // Refresh work experiences list
            $stmt = $pdo->prepare("SELECT * FROM student_work_experience WHERE student_id = ? ORDER BY start_date DESC");
            $stmt->execute([$student['id']]);
            $work_experiences = $stmt->fetchAll();
        } else {
            $error = 'No se pudo eliminar la experiencia laboral.';
        }
    }
}

$page_title = 'Experiencia Laboral';

$content = '
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title"></h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addExperienceModal">
                        <i class="fas fa-plus"></i> Agregar Experiencia
                    </button>
                </div>
            </div>
            <div class="card-body">
                ' . ($error ? '<div class="alert alert-danger">' . $error . '</div>' : '') . '
                ' . ($success ? '<div class="alert alert-success">' . $success . '</div>' : '') . '

                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Empresa</th>
                                <th>Cargo</th>
                                <th>Tipo</th>
                                <th>Duración</th>
                                <th>Lugar</th>
                                <th>Certificado</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>';

if (count($work_experiences) > 0) {
    foreach ($work_experiences as $exp) {
        $duration = '';
        if ($exp['current_job']) {
            $start = date('m/Y', strtotime($exp['start_date']));
            $duration = $start . ' - Presente';
        } else {
            $start = date('m/Y', strtotime($exp['start_date']));
            $end = $exp['end_date'] ? date('m/Y', strtotime($exp['end_date'])) : 'Presente';
            $duration = $start . ' - ' . $end;
        }

        $certificate_link = $exp['certificate_file'] ?
            '<a href="../' . htmlspecialchars($exp['certificate_file']) . '" target="_blank" class="btn btn-sm btn-info"><i class="fas fa-file-pdf"></i> Ver</a>' :
            '<span class="text-muted">Sin certificado</span>';

        $employment_type_map = [
            'full-time' => 'Tiempo Completo',
            'part-time' => 'Medio Tiempo',
            'contract' => 'Contrato',
            'freelance' => 'Freelance',
            'internship' => 'Pasantía',
            'volunteer' => 'Voluntario'
        ];

        $employment_type_display = $employment_type_map[$exp['employment_type']] ?? ucfirst(htmlspecialchars($exp['employment_type']));

        $content .= '<tr>
            <td><strong>' . htmlspecialchars($exp['company_name']) . '</strong></td>
            <td>' . htmlspecialchars($exp['job_title']) . '</td>
            <td>' . $employment_type_display . '</td>
            <td>' . $duration . '</td>
            <td>' . htmlspecialchars($exp['location'] ?: 'No especificado') . '</td>
            <td>' . $certificate_link . '</td>
            <td>
                <div class="btn-group">
                    <button type="button" class="btn btn-warning btn-sm" onclick="editExperience(' . $exp['id'] . ', \'' . addslashes($exp['company_name']) . '\', \'' . addslashes($exp['job_title']) . '\', \'' . addslashes($exp['employment_type']) . '\', \'' . addslashes($exp['location']) . '\', \'' . $exp['start_date'] . '\', \'' . $exp['end_date'] . '\', ' . $exp['current_job'] . ', \'' . addslashes($exp['salary_range']) . '\')">
                        <i class="fas fa-edit"></i> Editar
                    </button>
                    <form method="post" style="display: inline;">
                        <input type="hidden" name="experience_id" value="' . $exp['id'] . '">
                        <button type="submit" name="delete_experience" class="btn btn-danger btn-sm" onclick="return confirm(\'Estás seguro de que deseas eliminar esta experiencia laboral?\')">
                            <i class="fas fa-trash"></i> Borrar
                        </button>
                    </form>
                </div>
            </td>
        </tr>';
    }
} else {
    $content .= '<tr><td colspan="7" class="text-center text-muted">No work experience added yet. Click "Add Experience" to get started.</td></tr>';
}

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

<!-- Add Experience Modal -->
<div class="modal fade" id="addExperienceModal" tabindex="-1" role="dialog" aria-labelledby="addExperienceModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addExperienceModalLabel">Agregar Nueva Experiencia Laboral</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" enctype="multipart/form-data" id="experienceForm">
                <input type="hidden" name="experience_id" id="edit_experience_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="company_name">Nombre de la Empresa*</label>
                                <input type="text" class="form-control" id="company_name" name="company_name" required>
                            </div>
                            <div class="form-group">
                                <label for="job_title">Cargo *</label>
                                <input type="text" class="form-control" id="job_title" name="job_title" required>
                            </div>
                            <div class="form-group">
                                <label for="employment_type">Tipo de Trabajo</label>
                                <select class="form-control" id="employment_type" name="employment_type">
                                    <option value="full-time">Full-time</option>
                                    <option value="part-time">Part-time</option>
                                    <option value="contract">Contract</option>
                                    <option value="freelance">Freelance</option>
                                    <option value="internship">Internship</option>
                                    <option value="volunteer">Volunteer</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="location">Lugar</label>
                                <input type="text" class="form-control" id="location" name="location" placeholder="City, Country">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="start_date">Fecha de inicio *</label>
                                <input type="date" class="form-control" id="start_date" name="start_date" required>
                            </div>
                            <div class="form-group">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="current_job" name="current_job" onchange="toggleEndDate()">
                                    <label class="form-check-label" for="current_job">
                                        Sigo trabajando aquí
                                    </label>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="end_date">Fecha de fin</label>
                                <input type="date" class="form-control" id="end_date" name="end_date">
                            </div>
                            <div class="form-group">
                                <label for="salary_range">Sueldo (Rango)</label>
                                <input type="text" class="form-control" id="salary_range" name="salary_range" placeholder="e.g., $20,000 - $25,000 per year">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="certificate_file"> Certificado (PDF)</label>
                        <input type="file" class="form-control" id="certificate_file" name="certificate_file" accept=".pdf">
                        <small class="form-text text-muted">Upload your work certificate, letter of recommendation, or employment verification document. Max 10MB.</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_experience" id="submitBtn" class="btn btn-primary">Agregar Experiencia</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function toggleEndDate() {
    const currentJobCheckbox = document.getElementById(\'current_job\');
    const endDateField = document.getElementById(\'end_date\');

    if (currentJobCheckbox.checked) {
        endDateField.value = \'\';
        endDateField.disabled = true;
        endDateField.required = false;
    } else {
        endDateField.disabled = false;
        endDateField.required = false; // Optional field
    }
}

function editExperience(id, companyName, jobTitle, employmentType, location, startDate, endDate, currentJob, salaryRange) {
    document.getElementById(\'edit_experience_id\').value = id;
    document.getElementById(\'company_name\').value = companyName;
    document.getElementById(\'job_title\').value = jobTitle;
    document.getElementById(\'employment_type\').value = employmentType;
    document.getElementById(\'location\').value = location;
    document.getElementById(\'start_date\').value = startDate;
    document.getElementById(\'end_date\').value = endDate;
    document.getElementById(\'current_job\').checked = currentJob == 1;
    document.getElementById(\'salary_range\').value = salaryRange;
    document.getElementById(\'submitBtn\').name = \'edit_experience\';
    document.getElementById(\'submitBtn\').textContent = \'Actualizar Experiencia\';
    document.getElementById(\'addExperienceModalLabel\').textContent = \'Editar Experiencia Laboral\';
    $(\'#addExperienceModal\').modal(\'show\');
    toggleEndDate(); // Apply toggle logic after setting values
}

// Initialize on page load
document.addEventListener(\'DOMContentLoaded\', function() {
    toggleEndDate();
});

$(\'#addExperienceModal\').on(\'hidden.bs.modal\', function () {
    document.getElementById(\'experienceForm\').reset();
    document.getElementById(\'edit_experience_id\').value = \'\';
    document.getElementById(\'submitBtn\').name = \'add_experience\';
    document.getElementById(\'submitBtn\').textContent = \'Agregar Experiencia\';
    document.getElementById(\'addExperienceModalLabel\').textContent = \'Agregar Nueva Experiencia Laboral\';
});
</script>

<!-- Add Bootstrap and jQuery for modal functionality -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>';

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