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

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // Get form data
    $full_name = trim($_POST['full_name'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $license_number = trim($_POST['license_number'] ?? '');
    $specialization = $_POST['specialization'] ?? '';
    $ward = trim($_POST['ward'] ?? '');
    $qualifications = trim($_POST['qualifications'] ?? '');  // Changed from credentials
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // Validation
    $errors = [];
    if (empty($full_name)) $errors[] = "Full name is required";
    if (empty($username)) $errors[] = "Username is required";
    if (empty($email)) $errors[] = "Email is required";
    if (empty($phone)) $errors[] = "Phone number is required";
    if (empty($license_number)) $errors[] = "License number is required";
    if (empty($password)) $errors[] = "Password is required";
    if ($password !== $confirm_password) $errors[] = "Passwords do not match";
    if (strlen($password) < 6 && !empty($password)) $errors[] = "Password must be at least 6 characters";
    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format";
    
    if (empty($errors)) {
        // Check username
        $check = $conn->query("SELECT user_id FROM users WHERE username = '" . mysqli_real_escape_string($conn, $username) . "'");
        if ($check && $check->num_rows > 0) {
            $errors[] = "Username already exists";
        }
        
        // Check email
        $check_email = $conn->query("SELECT user_id FROM users WHERE email = '" . mysqli_real_escape_string($conn, $email) . "'");
        if ($check_email && $check_email->num_rows > 0) {
            $errors[] = "Email already registered";
        }
    }
    
    if (empty($errors)) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        // Insert into users table
        $sql1 = "INSERT INTO users (username, email, password, role, full_name, status, approval_status, created_at) 
                 VALUES (
                     '" . mysqli_real_escape_string($conn, $username) . "',
                     '" . mysqli_real_escape_string($conn, $email) . "',
                     '$hashed_password',
                     'nurse',
                     '" . mysqli_real_escape_string($conn, $full_name) . "',
                     'inactive',
                     'pending',
                     NOW()
                 )";
        
        if ($conn->query($sql1)) {
            $user_id = $conn->insert_id;
            $nurse_number = 'NRS' . str_pad($user_id, 4, '0', STR_PAD_LEFT);
            
            // Insert into nurses table - MATCHING YOUR DATABASE COLUMNS
            $sql2 = "INSERT INTO nurses (
                user_id, nurse_number, first_name, last_name, email, phone, 
                license_number, specialization, ward, qualifications, status, approval_status, created_at
            ) VALUES (
                $user_id,
                '$nurse_number',
                '" . mysqli_real_escape_string($conn, $full_name) . "',
                '',
                '" . mysqli_real_escape_string($conn, $email) . "',
                '" . mysqli_real_escape_string($conn, $phone) . "',
                '" . mysqli_real_escape_string($conn, $license_number) . "',
                '" . mysqli_real_escape_string($conn, $specialization) . "',
                '" . mysqli_real_escape_string($conn, $ward) . "',
                '" . mysqli_real_escape_string($conn, $qualifications) . "',
                'inactive',
                'pending',
                NOW()
            )";
            
            if ($conn->query($sql2)) {
                $success = "Registration successful! Your application is pending admin approval.";
            } else {
                $error = "Error saving nurse details: " . $conn->error;
                $conn->query("DELETE FROM users WHERE user_id = $user_id");
            }
        } else {
            $error = "Error creating account: " . $conn->error;
        }
    } else {
        $error = implode("<br>", $errors);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nurse Registration - Unity Healthcare</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, #3d2b1f 0%, #2c1a0e 100%);
            font-family: 'Segoe UI', sans-serif;
            min-height: 100vh;
            padding: 50px 0;
        }
        .register-card {
            background: #2c1a0e;
            border: 1px solid #d4a017;
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.3);
            max-width: 650px;
            margin: 0 auto;
        }
        .register-header {
            background: linear-gradient(135deg, #1a0f08, #2c1a0e);
            color: #d4a017;
            padding: 25px;
            text-align: center;
            border-bottom: 2px solid #d4a017;
            border-radius: 20px 20px 0 0;
        }
        .register-header i { font-size: 50px; margin-bottom: 10px; }
        .register-header h2 { margin: 0; }
        .register-header p { color: #c0c0c0; margin: 5px 0 0; }
        .register-body { padding: 30px; }
        .form-control, .form-select {
            background: #3d2b1f;
            border: 1px solid #d4a017;
            color: white;
            padding: 10px 12px;
            border-radius: 8px;
        }
        .form-control:focus, .form-select:focus {
            background: #4a3828;
            border-color: #d4a017;
            box-shadow: 0 0 5px #d4a017;
            outline: none;
        }
        .form-label { color: #d4a017; font-weight: 500; margin-bottom: 5px; font-size: 13px; }
        .btn-register {
            background: #d4a017;
            color: #1a0f08;
            border: none;
            padding: 12px;
            font-weight: bold;
            font-size: 16px;
            border-radius: 8px;
            width: 100%;
            cursor: pointer;
            transition: 0.3s;
        }
        .btn-register:hover { background: #b8860b; color: white; }
        .alert { border-radius: 8px; margin-bottom: 20px; padding: 12px; }
        .required:after { content: " *"; color: #dc3545; }
        .text-warning { color: #d4a017 !important; }
        .row { display: flex; gap: 15px; margin-bottom: 10px; }
        .col { flex: 1; }
        @media (max-width: 768px) {
            .row { flex-direction: column; gap: 0; }
            .register-card { margin: 10px; }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="register-card">
        <div class="register-header">
            <i class="fas fa-user-nurse"></i>
            <h2>Nurse Registration</h2>
            <p>Join the Unity Healthcare Nursing Team</p>
        </div>
        <div class="register-body">
            <?php if($error): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i> <?= $error ?>
                </div>
            <?php endif; ?>
            
            <?php if($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> <?= $success ?>
                </div>
                <div class="text-center mt-3">
                    <a href="login.php" class="btn btn-warning">Go to Login</a>
                </div>
            <?php else: ?>
                <form method="POST" id="registerForm">
                    <div class="mb-3">
                        <label class="form-label required">Full Name</label>
                        <input type="text" name="full_name" class="form-control" value="<?= htmlspecialchars($_POST['full_name'] ?? '') ?>" required>
                    </div>
                    
                    <div class="row">
                        <div class="col">
                            <label class="form-label required">Username</label>
                            <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" required>
                        </div>
                        <div class="col">
                            <label class="form-label required">Email</label>
                            <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col">
                            <label class="form-label required">Phone</label>
                            <input type="tel" name="phone" class="form-control" value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>" required>
                        </div>
                        <div class="col">
                            <label class="form-label required">License Number</label>
                            <input type="text" name="license_number" class="form-control" placeholder="e.g., RN-12345" value="<?= htmlspecialchars($_POST['license_number'] ?? '') ?>" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col">
                            <label class="form-label">Specialization</label>
                            <select name="specialization" class="form-select">
                                <option value="">Select Specialization</option>
                                <option value="General Nursing">General Nursing</option>
                                <option value="Pediatric Nursing">Pediatric Nursing</option>
                                <option value="Critical Care">Critical Care</option>
                                <option value="Emergency Nursing">Emergency Nursing</option>
                                <option value="Psychiatric Nursing">Psychiatric Nursing</option>
                                <option value="Midwifery">Midwifery</option>
                                <option value="Perioperative">Perioperative Nursing</option>
                            </select>
                        </div>
                        <div class="col">
                            <label class="form-label">Assigned Ward</label>
                            <input type="text" name="ward" class="form-control" placeholder="e.g., General Ward, ICU" value="<?= htmlspecialchars($_POST['ward'] ?? '') ?>">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Qualifications</label>
                        <input type="text" name="qualifications" class="form-control" placeholder="e.g., BSN, RN, MSN" value="<?= htmlspecialchars($_POST['qualifications'] ?? '') ?>">
                    </div>
                    
                    <div class="row">
                        <div class="col">
                            <label class="form-label required">Password</label>
                            <input type="password" name="password" id="password" class="form-control" required>
                            <small class="text-muted">Minimum 6 characters</small>
                        </div>
                        <div class="col">
                            <label class="form-label required">Confirm Password</label>
                            <input type="password" name="confirm_password" id="confirm_password" class="form-control" required>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn-register mt-3">
                        <i class="fas fa-paper-plane"></i> Submit Application
                    </button>
                </form>
                
                <div class="text-center mt-3">
                    <a href="login.php" class="text-warning">Already have an account? Login here</a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.getElementById('registerForm')?.addEventListener('submit', function(e) {
    var pass = document.getElementById('password').value;
    var conf = document.getElementById('confirm_password').value;
    
    if (pass !== conf) {
        e.preventDefault();
        alert('Passwords do not match!');
        return false;
    }
    
    if (pass.length < 6) {
        e.preventDefault();
        alert('Password must be at least 6 characters!');
        return false;
    }
    
    var btn = document.querySelector('.btn-register');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Submitting...';
    return true;
});
</script>
</body>
</html>