<?php
/**
 * Portal del Paciente - Acceso Externo
 * URL: https://sertca.com/patient-login.php
 */

define("ROOT", dirname(__FILE__));
define("IS_PATIENT_PORTAL", true);

$debug = false;
if ($debug) {
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
}

include "core/autoload.php";
ob_start();
session_start();
Core::$root = "";

// Load required models
require_once "core/app/model/PortalData.php";
require_once "core/app/model/ReservationData.php";
require_once "core/app/model/PacientData.php";
require_once "core/app/model/MedicData.php";

$view = isset($_GET['view']) ? $_GET['view'] : '';

if ($view === 'patient-portal') {
    $pacientId = isset($_SESSION['pacient_id']) ? $_SESSION['pacient_id'] : null;
    if (!$pacientId) {
        header("Location: patient-login.php");
        exit;
    }
    
    $pacient = PacientData::getById($pacientId);
    $notifications = PortalData::getNotifications($pacientId, true);
    $upcomingAppointments = ReservationData::getUpcomingByPacient($pacientId);
    $pastSessions = ReservationData::getPastByPacient($pacientId);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Portal del Paciente - Cedimik</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { background: #f8f9fa; }
        .header-gradient {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
        }
        .border-start { border-left: 4px solid !important; }
    </style>
</head>
<body>
    <div class="container py-4">
        <div class="card">
            <div class="card-header header-gradient text-white">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h4 class="mb-0"><i class="fa fa-user-circle"></i> Bienvenido, <?php echo htmlspecialchars(PacientData::fullName($pacient) ?: 'Paciente'); ?></h4>
                        <small>Portal del Paciente - Cedimik</small>
                    </div>
                    <a href="patient-login.php?logout=1" class="btn btn-light btn-sm">
                        <i class="fa fa-sign-out"></i> Salir
                    </a>
                </div>
            </div>
            <div class="card-body">
                <?php if (count($notifications ?? []) > 0): ?>
                    <div class="alert alert-info">
                        <i class="fa fa-bell"></i> Tenés <?php echo count($notifications); ?> notificación(es) sin leer
                    </div>
                <?php endif; ?>

                <div class="row">
                    <div class="col-md-6">
                        <div class="card border-start border-primary mb-3">
                            <div class="card-body">
                                <h5><i class="fa fa-calendar"></i> Próximos Turnos</h5>
                                <?php if (count($upcomingAppointments ?? []) > 0): ?>
                                    <table class="table table-sm">
                                        <?php foreach ($upcomingAppointments as $a): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo date('d/m/Y', strtotime($a->date_at)); ?></strong>
                                                    <br><small><?php echo date('H:i', strtotime($a->time_at)); ?></small>
                                                </td>
                                                <td><?php $medic = MedicData::getById($a->medic_id); echo htmlspecialchars($medic->name ?? '-'); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </table>
                                <?php else: ?>
                                    <p class="text-muted">No tenés turnos programados</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card border-start border-warning mb-3">
                            <div class="card-body">
                                <h5><i class="fa fa-bell"></i> Notificaciones</h5>
                                <?php if (count($notifications ?? []) > 0): ?>
                                    <ul class="list-group">
                                        <?php foreach (array_slice($notifications, 0, 5) as $n): ?>
                                            <li class="list-group-item"><?php echo htmlspecialchars($n->title ?? ''); ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p class="text-muted">No tenés notificaciones nuevas</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-body">
                        <h5><i class="fa fa-history"></i> Historial de Sesiones</h5>
                        <?php if (count($pastSessions ?? []) > 0): ?>
                            <table class="table table-striped">
                                <thead><tr><th>Fecha</th><th>Profesional</th><th>Estado</th></tr></thead>
                                <tbody>
                                    <?php foreach (array_slice($pastSessions, 0, 10) as $s): ?>
                                        <tr>
                                            <td><?php echo date('d/m/Y', strtotime($s->date_at)); ?></td>
                                            <td><?php $medic = MedicData::getById($s->medic_id); echo htmlspecialchars($medic->name ?? '-'); ?></td>
                                            <td><span class="badge bg-<?php echo $s->status_id == 4 ? 'success' : 'secondary'; ?>"><?php echo $s->status_id == 4 ? 'Completada' : 'Otra'; ?></span></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php else: ?>
                            <p class="text-muted">No tenés sesiones previas</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <div class="text-center mt-4">
            <small class="text-muted">Cedimik - Sostener, Escuchar, Renacer</small>
        </div>
    </div>
</body>
</html>
<?php
    exit;
}

if (isset($_GET['logout'])) {
    unset($_SESSION['pacient_id']);
    header("Location: patient-login.php");
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    
    $portal = PortalData::getByEmail($email);
    if ($portal && password_verify($password, $portal->password_hash)) {
        $_SESSION['pacient_id'] = $portal->pacient_id;
        header("Location: patient-login.php?view=patient-portal");
        exit;
    } else {
        $error = 'Email o contraseña incorrectos';
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Portal del Paciente - Cedimik</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; }
        .card { border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.2); }
    </style>
</head>
<body>
    <div class="d-flex align-items-center justify-content-center min-vh-100">
        <div class="card" style="width: 400px;">
            <div class="card-header bg-primary text-white text-center py-4">
                <h4 class="mb-0"><i class="fa fa-user-circle"></i> Portal del Paciente</h4>
                <small>Cedimik - Sostener, Escuchar, Renacer</small>
            </div>
            <div class="card-body p-4">
                <p class="text-muted text-center">Ingresá tus datos para acceder</p>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <form method="post">
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Contraseña</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Ingresar</button>
                </form>
            </div>
            <div class="card-footer text-center">
                <small><a href="https://sertca.com" class="text-muted">← Volver al sistema</a></small>
            </div>
        </div>
    </div>
</body>
</html>
