<?php
    ob_start();
    session_start();
    
    if(!isset($_SESSION['user_type']) || $_SESSION['user_type'] != 'ciudadano'){
        header('location: ../login.php');
        exit;
    }
    
    require_once('../../backend/bd/Conexion.php');
    global $connect;
    
    $username = $_SESSION['username'];
    $name = $_SESSION['name'];
    $cedula = $_SESSION['email']; // La cédula está guardada en el campo email
    
    // Verificar si ya completó la inscripción
    try {
        $stmt = $connect->prepare("SELECT * FROM patients WHERE numhs = :cedula");
        $stmt->execute([':cedula' => $cedula]);
        $datos_paciente = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if($datos_paciente) {
            // Ya completó la inscripción, redirigir al dashboard
            header('location: dashboard.php');
            exit;
        }
    } catch(PDOException $e) {
        // Error al consultar
    }
    
    // Separar nombre y apellido
    $nombre_completo = explode(' ', $name, 2);
    $nombres = $nombre_completo[0] ?? '';
    $apellidos = $nombre_completo[1] ?? '';
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href='https://unpkg.com/boxicons@2.0.9/css/boxicons.min.css' rel='stylesheet'>
    <link rel="icon" type="image/png" sizes="96x96" href="../../backend/img/ico.svg">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.css">
    
    <title>Inscripción - Programa Persona Mayor</title>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.2);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 40px 30px;
            text-align: center;
            color: white;
        }

        .header h1 {
            font-size: 32px;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 16px;
            opacity: 0.9;
        }

        .form-content {
            padding: 40px 30px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-section h2 {
            font-size: 22px;
            color: #667eea;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 3px solid #667eea;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }

        .form-group label .required {
            color: #e74c3c;
            margin-left: 3px;
        }

        .form-group input[type="text"],
        .form-group input[type="email"],
        .form-group input[type="date"],
        .form-group input[type="file"],
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-group input:disabled {
            background: #f5f5f5;
            cursor: not-allowed;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }

        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }

        .btn-submit {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
        }

        .btn-back {
            display: inline-block;
            padding: 12px 25px;
            background: transparent;
            border: 2px solid #667eea;
            color: #667eea;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
            margin-bottom: 20px;
        }

        .btn-back:hover {
            background: #667eea;
            color: white;
        }

        .img-preview {
            max-width: 200px;
            max-height: 200px;
            margin-top: 10px;
            border-radius: 10px;
            display: none;
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 600;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left: 5px solid #28a745;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border-left: 5px solid #dc3545;
        }

        hr {
            border: none;
            border-top: 2px solid #e0e0e0;
            margin: 30px 0;
        }

        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }

            .header h1 {
                font-size: 24px;
            }

            .form-content {
                padding: 30px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class='bx bxs-edit'></i> Formulario de Inscripción</h1>
            <p>PROGRAMA MUNICIPAL PERSONA MAYOR</p>
            <p>Complete sus datos para finalizar la inscripción al programa</p>
        </div>

        <div class="form-content">
            <a href="dashboard.php" class="btn-back">
                <i class='bx bx-arrow-back'></i> Volver al Dashboard
            </a>

            <?php include_once '../../backend/php/inscripcion_ciudadano.php'; ?>

            <form action="" method="POST" enctype="multipart/form-data" id="inscripcionForm">
                
                <!-- Información Personal -->
                <div class="form-section">
                    <h2><i class='bx bxs-user'></i> Información Personal</h2>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Tipo de Documento <span class="required">*</span></label>
                            <select required name="tdocumento" id="tdocumento">
                                <option value="">Seleccione</option>
                                <option value="CC" selected>Cédula de Ciudadanía</option>
                                <option value="TI">Tarjeta de Identidad</option>
                                <option value="CE">Cédula de Extranjería</option>
                                <option value="PA">Pasaporte</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Número de Documento <span class="required">*</span></label>
                            <input type="text" value="<?php echo $cedula; ?>" name="nhi" maxlength="30" required disabled>
                            <input type="hidden" name="nhi" value="<?php echo $cedula; ?>">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Nombres <span class="required">*</span></label>
                            <input type="text" value="<?php echo $nombres; ?>" placeholder="Nombres completos" name="namp" maxlength="50" required>
                        </div>

                        <div class="form-group">
                            <label>Apellidos <span class="required">*</span></label>
                            <input type="text" value="<?php echo $apellidos; ?>" placeholder="Apellidos completos" name="apep" maxlength="50" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Fecha de Nacimiento <span class="required">*</span></label>
                            <input type="date" name="cump" required>
                        </div>

                        <div class="form-group">
                            <label>Género <span class="required">*</span></label>
                            <select required name="gep" id="gep">
                                <option value="">Seleccione</option>
                                <option value="MASCULINO">Masculino</option>
                                <option value="FEMENINO">Femenino</option>
                                <option value="OTRO">Otro</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Foto de Perfil</label>
                        <input type="file" name="fotoperfil" id="fotoperfil" accept="image/*">
                        <img id="img-preview" class="img-preview" alt="Vista previa">
                    </div>
                </div>

                <hr>

                <!-- Información de Contacto -->
                <div class="form-section">
                    <h2><i class='bx bxs-phone'></i> Información de Contacto</h2>
                    
                    <div class="form-group">
                        <label>Dirección <span class="required">*</span></label>
                        <input type="text" placeholder="Dirección completa" name="dip" required>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Teléfono <span class="required">*</span></label>
                            <input type="text" maxlength="13" placeholder="+57 300 123 4567" name="telp" required>
                        </div>

                        <div class="form-group">
                            <label>¿Tiene WhatsApp? <span class="required">*</span></label>
                            <select required name="tiene_whatsapp" id="tiene_whatsapp">
                                <option value="">Seleccione</option>
                                <option value="SI">Sí</option>
                                <option value="NO">No</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Correo Electrónico <span class="required">*</span></label>
                        <input type="email" placeholder="correo@ejemplo.com" name="correo" maxlength="70" required>
                    </div>
                </div>

                <hr>

                <!-- Información Adicional -->
                <div class="form-section">
                    <h2><i class='bx bxs-info-circle'></i> Información Adicional</h2>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Grupo Sanguíneo <span class="required">*</span></label>
                            <select required name="grp" id="grp">
                                <option value="">Seleccione</option>
                                <option value="A+">A+</option>
                                <option value="A-">A-</option>
                                <option value="B+">B+</option>
                                <option value="B-">B-</option>
                                <option value="AB+">AB+</option>
                                <option value="AB-">AB-</option>
                                <option value="O+">O+</option>
                                <option value="O-">O-</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Estado Civil <span class="required">*</span></label>
                            <select required name="ecivil" id="ecivil">
                                <option value="">Seleccione</option>
                                <option value="SOLTERO">Soltero(a)</option>
                                <option value="CASADO">Casado(a)</option>
                                <option value="UNION LIBRE">Unión Libre</option>
                                <option value="VIUDO">Viudo(a)</option>
                                <option value="DIVORCIADO">Divorciado(a)</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Observaciones</label>
                        <textarea name="observacionsalida" placeholder="Información adicional que desee compartir"></textarea>
                    </div>
                </div>

                <button type="submit" name="inscripcion_ciudadano" class="btn-submit">
                    <i class='bx bx-check-circle'></i> Completar Inscripción
                </button>
            </form>
        </div>
    </div>

    <script src="../../backend/js/jquery.min.js"></script>

    <script>
        // Previsualizar imagen
        document.getElementById('fotoperfil').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const preview = document.getElementById('img-preview');
            
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                }
                reader.readAsDataURL(file);
            } else {
                preview.style.display = 'none';
            }
        });
    </script>
</body>
</html>
