<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include '../include/config.php';

$error = '';
$success = '';

// Generate unique patient ID
function generatePatientId($conn) {
    $prefix = 'P' . date('Ymd');
    $random = rand(100, 999);
    $patient_id = $prefix . $random;
    
    // Check if exists
    $check = $conn->query("SELECT patient_id FROM patients WHERE patient_id = '$patient_id'");
    if ($check->num_rows > 0) {
        return generatePatientId($conn);
    }
    return $patient_id;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $custom_pin = trim($_POST['custom_pin']);
    $confirm_pin = trim($_POST['confirm_pin']);
    $dob = trim($_POST['dob'] ?? '');
    $gender = trim($_POST['gender'] ?? '');
    $address = trim($_POST['address'] ?? '');
    
    // Validate PIN
    if (!preg_match('/^[0-9]{4}$/', $custom_pin)) {
        $error = "PIN must be exactly 4 digits (0-9 only).";
    } elseif ($custom_pin !== $confirm_pin) {
        $error = "PINs do not match!";
    } elseif ($password !== $confirm_password) {
        $error = "Passwords do not match!";
    } elseif (strlen($password) < 6) {
        $error = "Password must be at least 6 characters.";
    } else {
        // Check if email exists
        $check = $conn->prepare("SELECT email FROM patients WHERE email = ?");
        $check->bind_param("s", $email);
        $check->execute();
        $check->store_result();
        
        if ($check->num_rows > 0) {
            $error = "Email already registered!";
        } else {
            // Generate patient ID
            $patient_id = generatePatientId($conn);
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $status = 'active'; // Auto activate - NO PAYMENT NEEDED
            $portal_active = 1;
            
            $stmt = $conn->prepare("INSERT INTO patients (patient_id, first_name, last_name, email, phone, password, login_pin, dob, gender, address, status, portal_active, created_at) 
                                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->bind_param("sssssssssssi", 
                $patient_id, $first_name, $last_name, $email, $phone, 
                $hashed_password, $custom_pin, $dob, $gender, $address, 
                $status, $portal_active
            );
            
            if ($stmt->execute()) {
                // Get the inserted patient ID
                $patient_db_id = $stmt->insert_id;
                
                // Auto login - Set session variables
                $_SESSION['patient_id'] = $patient_db_id;
                $_SESSION['patient_uid'] = $patient_id;
                $_SESSION['patient_name'] = $first_name . ' ' . $last_name;
                $_SESSION['patient_email'] = $email;
                $_SESSION['user_role'] = 'patient';
                $_SESSION['user_id'] = $patient_db_id;
                
                // Store PIN for quick login
                $_SESSION['patient_pin'] = $custom_pin;
                
                // Redirect to dashboard immediately
                header("Location: dashboard.php");
                exit();
            } else {
                $error = "Registration failed: " . $conn->error;
            }
            $stmt->close();
        }
        $check->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Patient Registration - UHD</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: linear-gradient(135deg, #0a3d2f, #064e3b); font-family: 'Segoe UI', sans-serif; min-height: 100vh; }
        .register-card { background: white; border-radius: 20px; max-width: 600px; margin: 30px auto; overflow: hidden; box-shadow: 0 20px 40px rgba(0,0,0,0.2); }
        .card-header { background: linear-gradient(135deg, #0f6b4c, #064e3b); color: white; text-align: center; padding: 25px; }
        .card-header i { font-size: 3rem; margin-bottom: 10px; }
        .card-body { padding: 30px; }
        .btn-register { background: #0f6b4c; border: none; border-radius: 30px; padding: 12px; font-weight: bold; }
        .btn-register:hover { background: #0a523b; color: white; }
        .form-control { border-radius: 12px; padding: 12px; }
        .form-select { border-radius: 12px; padding: 12px; }
        .pin-input { text-align: center; font-size: 1.3rem; letter-spacing: 5px; font-weight: bold; }
        .pin-hint { font-size: 12px; color: #6c757d; margin-top: 5px; }
        .benefits-box { background: #f8f9fa; border-radius: 12px; padding: 15px; margin-top: 20px; }
        .benefits-box h6 { color: #0a3d2f; margin-bottom: 10px; }
        .benefits-box ul { margin-bottom: 0; padding-left: 20px; }
        .benefits-box li { margin-bottom: 5px; font-size: 0.85rem; }
        @media (max-width: 768px) { .container { padding: 10px; } .register-card { margin: 20px auto; } }
    </style>
</head>
<body>
<div class="container">
    <div class="register-card">
        <div class="card-header">
            <i class="fas fa-user-plus"></i>
            <h2>Patient Registration</h2>
            <p>Create your UHD Patient Account - <strong class="text-warning">FREE</strong></p>
        </div>
        <div class="card-body">
            <?php if($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-triangle me-2"></i> <?= htmlspecialchars($error) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <form method="POST">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold"><i class="fas fa-user"></i> First Name *</label>
                        <input type="text" name="first_name" class="form-control" required placeholder="John">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold"><i class="fas fa-user"></i> Last Name *</label>
                        <input type="text" name="last_name" class="form-control" required placeholder="Doe">
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold"><i class="fas fa-envelope"></i> Email Address *</label>
                        <input type="email" name="email" class="form-control" required placeholder="your@email.com">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold"><i class="fas fa-phone"></i> Phone Number</label>
                        <input type="tel" name="phone" class="form-control" placeholder="08012345678">
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold"><i class="fas fa-calendar"></i> Date of Birth</label>
                        <input type="date" name="dob" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold"><i class="fas fa-venus-mars"></i> Gender</label>
                        <select name="gender" class="form-select">
                            <option value="">Select Gender</option>
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-semibold"><i class="fas fa-home"></i> Address</label>
                    <textarea name="address" class="form-control" rows="2" placeholder="Your residential address"></textarea>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold"><i class="fas fa-lock"></i> Password *</label>
                        <input type="password" name="password" class="form-control" required minlength="6">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold"><i class="fas fa-lock"></i> Confirm Password *</label>
                        <input type="password" name="confirm_password" class="form-control" required>
                    </div>
                </div>
                
                <div class="alert alert-info small">
                    <i class="fas fa-info-circle"></i> 
                    <strong>Private PIN Login:</strong> You will use this 4-digit PIN to quickly access your portal without email/password.
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold"><i class="fas fa-key"></i> Set 4-Digit PIN *</label>
                        <input type="password" name="custom_pin" class="form-control pin-input" maxlength="4" pattern="[0-9]{4}" required placeholder="●●●●">
                        <div class="pin-hint">Choose any 4-digit number (e.g., 1234)</div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold"><i class="fas fa-check-circle"></i> Confirm PIN *</label>
                        <input type="password" name="confirm_pin" class="form-control pin-input" maxlength="4" pattern="[0-9]{4}" required placeholder="●●●●">
                    </div>
                </div>
                
                <div class="form-check mb-3">
                    <input type="checkbox" class="form-check-input" id="terms" required>
                    <label class="form-check-label" for="terms">
                        I agree to the <a href="/terms.php">Terms of Service</a> and <a href="/privacy.php">Privacy Policy</a>
                    </label>
                </div>
                
                <button type="submit" class="btn btn-register w-100">
                    <i class="fas fa-user-plus me-2"></i> Register Free
                </button>
            </form>
            
            <div class="benefits-box">
                <h6><i class="fas fa-gift me-2" style="color: #d4a017;"></i> Free Registration Includes:</h6>
                <ul>
                    <li><i class="fas fa-check-circle text-success me-2"></i> Book appointments with doctors</li>
                    <li><i class="fas fa-check-circle text-success me-2"></i> Access your medical records</li>
                    <li><i class="fas fa-check-circle text-success me-2"></i> Virtual consultations</li>
                    <li><i class="fas fa-check-circle text-success me-2"></i> Receive prescriptions online</li>
                    <li><i class="fas fa-check-circle text-success me-2"></i> AI health assistant (3 queries/day)</li>
                    <li><i class="fas fa-check-circle text-success me-2"></i> Track health vitals</li>
                </ul>
            </div>
            
            <div class="text-center mt-3">
                <small>Already have an account? <a href="private_login.php" class="text-success">Login with PIN</a> | <a href="login.php" class="text-success">Email Login</a></small>
            </div>
        </div>
    </div>
</div>

<script>
// PIN input - allow only numbers
document.querySelectorAll('.pin-input').forEach(input => {
    input.addEventListener('input', function(e) {
        this.value = this.value.replace(/[^0-9]/g, '').slice(0, 4);
    });
});

// Password confirmation validation
document.querySelector('form').addEventListener('submit', function(e) {
    var password = document.querySelector('input[name="password"]').value;
    var confirm = document.querySelector('input[name="confirm_password"]').value;
    if (password !== confirm) {
        e.preventDefault();
        alert('Passwords do not match!');
    }
});
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>