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

check_role('administrador');

$user = get_logged_in_user();

$error = '';
$success = '';
$edit_career = null;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_career'])) {
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);

        if (empty($name)) {
            $error = 'El nombre del programa es obligatorio.';
        } else {
            // Check if career already exists
            $stmt = $pdo->prepare("SELECT id FROM careers WHERE name = ?");
            $stmt->execute([$name]);
            if ($stmt->fetch()) {
                $error = 'El programa ya existe.';
            } else {
                $stmt = $pdo->prepare("INSERT INTO careers (name, description) VALUES (?, ?)");
                if ($stmt->execute([$name, $description])) {
                    $success = 'Programa agregada exitosamente.';
                } else {
                    $error = 'No se pudo agregar el programa.';
                }
            }
        }
    } elseif (isset($_POST['edit_career'])) {
        $id = $_POST['career_id'];
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);

        if (empty($name)) {
            $error = 'El nombre del programa es obligatorio.';
        } else {
            // Check if career name already exists (excluding current)
            $stmt = $pdo->prepare("SELECT id FROM careers WHERE name = ? AND id != ?");
            $stmt->execute([$name, $id]);
            if ($stmt->fetch()) {
                $error = 'El nombre del programa ya existe.';
            } else {
                $stmt = $pdo->prepare("UPDATE careers SET name = ?, description = ? WHERE id = ?");
                if ($stmt->execute([$name, $description, $id])) {
                    $success = 'El programa se actualizado con éxito.';
                } else {
                    $error = 'No se pudo actualizar la carrera.';
                }
            }
        }
    } elseif (isset($_POST['delete_career'])) {
        $id = $_POST['career_id'];

        // Check if career is being used by students
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM students WHERE career_id = ?");
        $stmt->execute([$id]);
        $usage_count = $stmt->fetch()['count'];

        if ($usage_count > 0) {
            $error = 'Cannot delete career. It is currently assigned to ' . $usage_count . ' student(s).';
        } else {
            $stmt = $pdo->prepare("DELETE FROM careers WHERE id = ?");
            if ($stmt->execute([$id])) {
                $success = 'Programa eliminada con éxito.';
            } else {
                $error = 'No se pudo eliminar el programa.';
            }
        }
    }
}

// Handle edit request
if (isset($_GET['edit'])) {
    $edit_id = $_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM careers WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_career = $stmt->fetch();
}

// Get all careers with job counts
$careers = $pdo->query("
    SELECT c.*,
           COUNT(DISTINCT s.id) as student_count,
           COUNT(DISTINCT j.id) as job_count
    FROM careers c
    LEFT JOIN students s ON c.id = s.career_id
    LEFT JOIN jobs j ON c.id = j.career_id AND j.status = 'active' AND j.deleted_at IS NULL
    GROUP BY c.id
    ORDER BY c.name
")->fetchAll();

$page_title = 'Administración de Programas';

$content = '
<div class="row">
    <div class="col-md-4">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">' . ($edit_career ? 'Editar ' : 'Agregar Programa') . '</h3>
            </div>
            <form method="post">
                <div class="card-body">
                    ' . ($error ? '<div class="alert alert-danger">' . $error . '</div>' : '') . '
                    ' . ($success ? '<div class="alert alert-success">' . $success . '</div>' : '') . '
                    ' . ($edit_career ? '<input type="hidden" name="career_id" value="' . $edit_career['id'] . '">' : '') . '
                    <div class="form-group">
                        <label for="name">Nombre *</label>
                        <input type="text" class="form-control" id="name" name="name" value="' . ($edit_career ? htmlspecialchars($edit_career['name']) : '') . '" required>
                    </div>
                    <div class="form-group">
                        <label for="description">Descripción</label>
                        <textarea class="form-control" id="description" name="description" rows="3" placeholder="Siglas...">' . ($edit_career ? htmlspecialchars($edit_career['description'] ?? '') : '') . '</textarea>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" name="' . ($edit_career ? 'edit_career' : 'add_career') . '" class="btn btn-primary">' . ($edit_career ? 'Editar' : 'Agregar') . '</button>
                    ' . ($edit_career ? '<a href="careers.php" class="btn btn-secondary">Cancel</a>' : '') . '
                </div>
            </form>
        </div>

    </div>

    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Ptogramas</h3>
            </div>
            <div class="card-body">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Nombre</th>
                            <th>Descripción</th>
                            <th>Estudiantes</th>
                            <th>Ofertas</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>';

foreach ($careers as $career) {
    $content .= '<tr>
        <td>' . $career['id'] . '</td>
        <td>' . htmlspecialchars($career['name']) . '</td>
        <td>' . htmlspecialchars($career['description'] ?? '') . '</td>
        <td>' . $career['student_count'] . '</td>
        <td>' . $career['job_count'] . '</td>
        <td>
            <a href="careers.php?edit=' . $career['id'] . '" class="btn btn-warning btn-sm"><i class="fas fa-edit   "></i> </a>
            <form method="post" style="display: inline;">
                <input type="hidden" name="career_id" value="' . $career['id'] . '">
                <button type="submit" name="delete_career" class="btn btn-danger btn-sm" onclick="return confirm(\'Are you sure you want to delete this career?\')"><i class="fas fa-trash"></i> </button>
            </form>
        </td>
    </tr>';
}

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

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