<?php
require_once 'config.php';

if (!empty($_SESSION['patient_id'])) {
    header('Location: ' . SITE_URL . '/patient/dashboard.php');
    exit;
}

// Redirect to landing page which has the register modal
header('Location: ' . SITE_URL . '/index.php#register');
exit;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Inputs
    $old['full_name'] = clean($_POST['full_name'] ?? '');
    $old['email'] = clean($_POST['email'] ?? '');
    $old['phone'] = clean($_POST['phone'] ?? '');
    $old['gender'] = clean($_POST['gender'] ?? '');
    $old['date_of_birth'] = clean($_POST['date_of_birth'] ?? '');
    $old['address'] = clean($_POST['address'] ?? '');
    $old['emergency_contact_name'] = clean($_POST['emergency_contact_name'] ?? '');
    $old['emergency_contact_phone'] = clean($_POST['emergency_contact_phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Validation
    if (empty($old['full_name'])) $errors[] = 'Full name zaroor bharo.';
    if (!filter_var($old['email'], FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email dalo.';
    if (strlen($old['phone']) < 10) $errors[] = 'Valid phone number dalo.';
    if (empty($old['gender'])) $errors[] = 'Gender select karo.';
    if (empty($old['date_of_birth'])) $errors[] = 'Date of birth dalo.';
    if (strlen($password) < 6) $errors[] = 'Password min 6 characters ka hona chahiye.';
    if ($password !== $confirm_password) $errors[] = 'Dono passwords match nahi karte.';

    // Duplicate check
    if (empty($errors)) {
        $stmt = $conn->prepare("SELECT id FROM patients WHERE email = ?");
        $stmt->bind_param('s', $old['email']);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $errors[] = 'Yeh email pehle se registered hai.';
        }
        $stmt->close();
    }

    // Save
    if (empty($errors)) {
        $health_id = generateHealthId($conn);
        $password_hash = password_hash($password, PASSWORD_BCRYPT);
        
        $stmt = $conn->prepare("
            INSERT INTO patients (health_id, full_name, email, phone, gender, date_of_birth, address, emergency_contact_name, emergency_contact_phone, password, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        $stmt->bind_param('ssssssssss', 
            $health_id, $old['full_name'], $old['email'], $old['phone'], 
            $old['gender'], $old['date_of_birth'], $old['address'], 
            $old['emergency_contact_name'], $old['emergency_contact_phone'], $password_hash
        );

        if ($stmt->execute()) {
            $patient_id = $conn->insert_id;
            $stmt->close();

            // Auto login
            $_SESSION['patient_id'] = $patient_id;
            $_SESSION['patient_name'] = $old['full_name'];
            $_SESSION['patient_email'] = $old['email'];
            $_SESSION['health_id'] = $health_id;

            setFlash('success', '✅ Registration successful! Welcome to HealthLink.');
            header('Location: ' . SITE_URL . '/patient/dashboard.php');
            exit;
        } else {
            $errors[] = 'Registration mein masla hua. Phir try karo.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ur">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Patient Registration - HealthLink</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-8 col-lg-6">
            <div class="card shadow">
                <div class="card-header bg-primary text-white text-center">
                    <h4><i class="fas fa-user-plus"></i> Patient Registration</h4>
                </div>
                <div class="card-body">
                    
                    <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                <?php foreach ($errors as $error): ?>
                                    <li><?= htmlspecialchars($error) ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label">Full Name *</label>
                            <input type="text" name="full_name" class="form-control" value="<?= htmlspecialchars($old['full_name'] ?? '') ?>" required>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email *</label>
                                <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($old['email'] ?? '') ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Phone *</label>
                                <input type="text" name="phone" class="form-control" value="<?= htmlspecialchars($old['phone'] ?? '') ?>" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Gender *</label>
                                <select name="gender" class="form-select" required>
                                    <option value="">Select Gender</option>
                                    <option value="male" <?= ($old['gender'] ?? '') === 'male' ? 'selected' : '' ?>>Male</option>
                                    <option value="female" <?= ($old['gender'] ?? '') === 'female' ? 'selected' : '' ?>>Female</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Date of Birth *</label>
                                <input type="date" name="date_of_birth" class="form-control" value="<?= htmlspecialchars($old['date_of_birth'] ?? '') ?>" required>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Address</label>
                            <textarea name="address" class="form-control" rows="3"><?= htmlspecialchars($old['address'] ?? '') ?></textarea>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Emergency Contact Name</label>
                                <input type="text" name="emergency_contact_name" class="form-control" value="<?= htmlspecialchars($old['emergency_contact_name'] ?? '') ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Emergency Contact Phone</label>
                                <input type="text" name="emergency_contact_phone" class="form-control" value="<?= htmlspecialchars($old['emergency_contact_phone'] ?? '') ?>">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Password *</label>
                                <input type="password" name="password" class="form-control" required>
                                <small class="text-muted">Min 6 characters</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Confirm Password *</label>
                                <input type="password" name="confirm_password" class="form-control" required>
                            </div>
                        </div>

                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-user-plus"></i> Register
                            </button>
                        </div>
                    </form>

                    <div class="text-center mt-3">
                        <p>Already have an account? <a href="<?= SITE_URL ?>/patient-login.php">Login here</a></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>