<?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'];
    
    // Obtener los datos del paciente
    $datos = null;
    $tiene_datos = false;
    
    try {
        $stmt = $connect->prepare("SELECT * FROM patients WHERE numhs = :cedula");
        $stmt->execute([':cedula' => $cedula]);
        $datos = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if($datos) {
            $tiene_datos = true;
        } else {
            // Si no tiene datos, redirigir a inscripción
            header('location: inscripcion.php');
            exit;
        }
    } catch(PDOException $e) {
        $error = "Error al cargar los datos: " . $e->getMessage();
    }
?>
<!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">
    <title>Mi Informació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;
        }

        .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;
        }

        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border-left: 5px solid #17a2b8;
        }

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

        .estado-badge {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-left: 10px;
        }

        .estado-pendiente {
            background: #fff3cd;
            color: #856404;
        }

        .estado-aprobado {
            background: #d4edda;
            color: #155724;
        }

        @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-user-circle'></i> Mi Información</h1>
            <p>PROGRAMA MUNICIPAL PERSONA MAYOR</p>
            <p>Consulta y actualiza tus datos personales</p>
        </div>

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

            <div class="alert alert-info">
                <strong><i class='bx bx-info-circle'></i> Información:</strong>
                Aquí puedes consultar y actualizar tus datos personales del programa.
            </div>

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

            <form action="" method="POST" enctype="multipart/form-data" id="miInfoForm">
                
                <!-- Información del Programa -->
                <div class="form-section">
                    <h2><i class='bx bxs-bookmark'></i> Información del Programa</h2>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Modalidad <span class="required">*</span></label>
                            <select required name="modalidad">
                                <option value="">Seleccione</option>
                                <option value="Centro día La paz" <?php echo ($datos['modalidad'] ?? '') == 'Centro día La paz' ? 'selected' : ''; ?>>Centro día La paz</option>
                                <option value="Centro día Bradamonte" <?php echo ($datos['modalidad'] ?? '') == 'Centro día Bradamonte' ? 'selected' : ''; ?>>Centro día Bradamonte</option>
                                <option value="Centro día Neruda G1" <?php echo ($datos['modalidad'] ?? '') == 'Centro día Neruda G1' ? 'selected' : ''; ?>>Centro día Neruda G1</option>
                                <option value="Centro día Neruda G2" <?php echo ($datos['modalidad'] ?? '') == 'Centro día Neruda G2' ? 'selected' : ''; ?>>Centro día Neruda G2</option>
                                <option value="Satélite san Miguel" <?php echo ($datos['modalidad'] ?? '') == 'Satélite san Miguel' ? 'selected' : ''; ?>>Satélite san Miguel</option>
                                <option value="Satélite perico" <?php echo ($datos['modalidad'] ?? '') == 'Satélite perico' ? 'selected' : ''; ?>>Satélite perico</option>
                                <option value="Club Santa Isabel" <?php echo ($datos['modalidad'] ?? '') == 'Club Santa Isabel' ? 'selected' : ''; ?>>Club Santa Isabel</option>
                                <option value="Club Renacer" <?php echo ($datos['modalidad'] ?? '') == 'Club Renacer' ? 'selected' : ''; ?>>Club Renacer</option>
                                <option value="Club San José" <?php echo ($datos['modalidad'] ?? '') == 'Club San José' ? 'selected' : ''; ?>>Club San José</option>
                                <option value="Club San Benito" <?php echo ($datos['modalidad'] ?? '') == 'Club San Benito' ? 'selected' : ''; ?>>Club San Benito</option>
                                <option value="Club San Rafael" <?php echo ($datos['modalidad'] ?? '') == 'Club San Rafael' ? 'selected' : ''; ?>>Club San Rafael</option>
                                <option value="RAD" <?php echo ($datos['modalidad'] ?? '') == 'RAD' ? 'selected' : ''; ?>>RAD</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Tipo de Usuario <span class="required">*</span></label>
                            <select required name="tusuario">
                                <option value="">Seleccione</option>
                                <option value="Antiguo" <?php echo ($datos['tusuario'] ?? '') == 'Antiguo' ? 'selected' : ''; ?>>Antiguo</option>
                                <option value="Nuevo" <?php echo ($datos['tusuario'] ?? '') == 'Nuevo' ? 'selected' : ''; ?>>Nuevo</option>
                            </select>
                        </div>
                    </div>
                </div>

                <hr>

                <!-- 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</label>
                            <input type="text" value="<?php echo $datos['tdocumento'] ?? ''; ?>" disabled>
                        </div>

                        <div class="form-group">
                            <label>Número de Documento</label>
                            <input type="text" value="<?php echo $datos['numhs'] ?? ''; ?>" disabled>
                            <input type="hidden" name="nhi" value="<?php echo $datos['numhs'] ?? ''; ?>">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Fecha de Expedición</label>
                            <input type="date" name="fexpedicion" value="<?php 
                            // Convertir formato DD/MM/YYYY a YYYY-MM-DD para input type="date"
                            $fecha_exp = $datos['fexpedicion'] ?? '';
                            if (!empty($fecha_exp) && strpos($fecha_exp, '/') !== false) {
                                $fecha_parts = explode('/', $fecha_exp);
                                if (count($fecha_parts) == 3) {
                                    echo $fecha_parts[2] . '-' . $fecha_parts[1] . '-' . $fecha_parts[0];
                                } else {
                                    echo $fecha_exp;
                                }
                            } else {
                                echo $fecha_exp;
                            }
                            ?>">
                        </div>

                        <div class="form-group">
                            <label>Lugar de Expedición</label>
                            <input type="text" name="lexpedicion" value="<?php echo $datos['lexpedicion'] ?? ''; ?>">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Nombres <span class="required">*</span></label>
                            <input type="text" value="<?php echo $datos['nompa'] ?? ''; ?>" name="namp" required>
                        </div>

                        <div class="form-group">
                            <label>Apellidos <span class="required">*</span></label>
                            <input type="text" value="<?php echo $datos['apepa'] ?? ''; ?>" name="apep" 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" value="<?php echo $datos['cump'] ?? ''; ?>" required>
                        </div>

                        <div class="form-group">
                            <label>Género <span class="required">*</span></label>
                            <select required name="gep">
                                <option value="">Seleccione</option>
                                <option value="MASCULINO" <?php echo ($datos['sex'] ?? '') == 'MASCULINO' ? 'selected' : ''; ?>>Masculino</option>
                                <option value="FEMENINO" <?php echo ($datos['sex'] ?? '') == 'FEMENINO' ? 'selected' : ''; ?>>Femenino</option>
                                <option value="BISEXUAL" <?php echo ($datos['sex'] ?? '') == 'BISEXUAL' ? 'selected' : ''; ?>>Bisexual</option>
                                <option value="INTERSEXUAL" <?php echo ($datos['sex'] ?? '') == 'INTERSEXUAL' ? 'selected' : ''; ?>>Intersexual</option>
                            </select>
                        </div>
                    </div>

                    <?php if(!empty($datos['fotoperfil'])): ?>
                    <div class="form-group">
                        <label>Foto de Perfil Actual</label>
                        <img src="../../uploads/fotos_perfil/<?php echo $datos['fotoperfil']; ?>" class="img-preview" alt="Foto de perfil">
                    </div>
                    <?php endif; ?>

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

                    <div class="form-row">
                        <div class="form-group">
                            <label>Grupo Sanguíneo <span class="required">*</span></label>
                            <select required name="grp">
                                <option value="">Seleccione</option>
                                <option value="A+" <?php echo ($datos['grup'] ?? '') == 'A+' ? 'selected' : ''; ?>>A+</option>
                                <option value="A-" <?php echo ($datos['grup'] ?? '') == 'A-' ? 'selected' : ''; ?>>A-</option>
                                <option value="B+" <?php echo ($datos['grup'] ?? '') == 'B+' ? 'selected' : ''; ?>>B+</option>
                                <option value="B-" <?php echo ($datos['grup'] ?? '') == 'B-' ? 'selected' : ''; ?>>B-</option>
                                <option value="AB+" <?php echo ($datos['grup'] ?? '') == 'AB+' ? 'selected' : ''; ?>>AB+</option>
                                <option value="AB-" <?php echo ($datos['grup'] ?? '') == 'AB-' ? 'selected' : ''; ?>>AB-</option>
                                <option value="O+" <?php echo ($datos['grup'] ?? '') == 'O+' ? 'selected' : ''; ?>>O+</option>
                                <option value="O-" <?php echo ($datos['grup'] ?? '') == 'O-' ? 'selected' : ''; ?>>O-</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Estado Civil <span class="required">*</span></label>
                            <select required name="ecivil">
                                <option value="">Seleccione</option>
                                <option value="SOLTERO" <?php echo ($datos['ecivil'] ?? '') == 'SOLTERO' ? 'selected' : ''; ?>>Soltero(a)</option>
                                <option value="CASADO" <?php echo ($datos['ecivil'] ?? '') == 'CASADO' ? 'selected' : ''; ?>>Casado(a)</option>
                                <option value="UNION LIBRE" <?php echo ($datos['ecivil'] ?? '') == 'UNION LIBRE' ? 'selected' : ''; ?>>Unión Libre</option>
                                <option value="VIUDO" <?php echo ($datos['ecivil'] ?? '') == 'VIUDO' ? 'selected' : ''; ?>>Viudo(a)</option>
                                <option value="DIVORCIADO" <?php echo ($datos['ecivil'] ?? '') == 'DIVORCIADO' ? 'selected' : ''; ?>>Divorciado(a)</option>
                            </select>
                        </div>
                    </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" value="<?php echo $datos['direc'] ?? ''; ?>" 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" value="<?php echo $datos['phon'] ?? ''; ?>" name="telp" required>
                        </div>

                        <div class="form-group">
                            <label>¿Tiene WhatsApp? <span class="required">*</span></label>
                            <select required name="tiene_whatsapp">
                                <option value="">Seleccione</option>
                                <option value="SI" <?php echo ($datos['tiene_whatsapp'] ?? '') == 'SI' ? 'selected' : ''; ?>>Sí</option>
                                <option value="NO" <?php echo ($datos['tiene_whatsapp'] ?? '') == 'NO' ? 'selected' : ''; ?>>No</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Correo Electrónico <span class="required">*</span></label>
                        <input type="email" value="<?php echo $datos['correo'] ?? ''; ?>" name="correo" required>
                    </div>
                </div>

                <button type="submit" name="actualizar_datos" class="btn-submit">
                    <i class='bx bx-save'></i> Guardar Cambios
                </button>
            </form>
        </div>
    </div>

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

    <script>
        // Previsualizar nueva imagen
        document.getElementById('fotoperfil').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const preview = document.getElementById('img-preview-new');
            
            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>
