<?php
require_once 'config.php';

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

// Registration is now handled via modal on landing page
header('Location: ' . SITE_URL . '/index.php#doctor-register');
exit;

// Get specializations
$specializations = $conn->query("SELECT id, name FROM specializations WHERE is_active = 1 ORDER BY name")->fetch_all(MYSQLI_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Input sanitization
    $old['full_name'] = clean($_POST['full_name'] ?? '');
    $old['email'] = clean($_POST['email'] ?? '');
    $old['phone'] = clean($_POST['phone'] ?? '');
    $old['gender'] = clean($_POST['gender'] ?? '');
    $old['pmc_license'] = clean($_POST['pmc_license'] ?? '');
    $old['specialization'] = (int)($_POST['specialization'] ?? 0);
    $old['qualification'] = clean($_POST['qualification'] ?? '');
    $old['experience'] = (int)($_POST['experience'] ?? 0);
    $old['consultation_fee'] = (float)($_POST['consultation_fee'] ?? 0);
    $old['clinic_name'] = clean($_POST['clinic_name'] ?? '');
    $old['clinic_address'] = clean($_POST['clinic_address'] ?? '');
    $old['city'] = clean($_POST['city'] ?? '');
    $old['bio'] = clean($_POST['bio'] ?? '');
    $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['pmc_license'])) $errors[] = 'PMC License Number zaroor hai.';
    if (empty($old['specialization'])) $errors[] = 'Specialization select karo.';
    if (empty($old['qualification'])) $errors[] = 'Qualification likho (MBBS, FCPS etc.)';
    if ($old['experience'] < 0) $errors[] = 'Experience valid number hona chahiye.';
    if ($old['consultation_fee'] <= 0) $errors[] = 'Consultation fee enter karo.';
    if (strlen($password) < 8) $errors[] = 'Password min 8 characters ka hona chahiye.';
    if (!preg_match('/[A-Z]/', $password)) $errors[] = 'Password mein ek capital letter hona chahiye.';
    if (!preg_match('/[0-9]/', $password)) $errors[] = 'Password mein ek number hona chahiye.';
    if ($password !== $confirm_password) $errors[] = 'Dono passwords match nahi karte.';

    // File validation
    $required_files = ['doc_license', 'doc_qualification', 'doc_cnic'];
    $uploaded_files = [];
    
    foreach ($required_files as $file_field) {
        if (empty($_FILES[$file_field]['name'])) {
            $errors[] = ucfirst(str_replace('doc_', '', $file_field)) . ' document upload karo.';
        } else {
            $file = $_FILES[$file_field];
            if ($file['error'] !== UPLOAD_ERR_OK) {
                $errors[] = ucfirst(str_replace('doc_', '', $file_field)) . ' upload mein masla hua.';
            } else {
                $uploaded_files[$file_field] = $file;
            }
        }
    }

    // Optional profile photo
    if (!empty($_FILES['profile_photo']['name'])) {
        $uploaded_files['profile_photo'] = $_FILES['profile_photo'];
    }

    // Check for duplicates
    if (empty($errors)) {
        $stmt = $conn->prepare("SELECT id FROM doctors WHERE email = ? OR pmc_license_number = ?");
        $stmt->bind_param('ss', $old['email'], $old['pmc_license']);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $errors[] = 'Yeh email ya PMC license number pehle se registered hai.';
        }
        $stmt->close();
    }

    // Save if no errors
    if (empty($errors)) {
        // Create uploads directory
        $upload_dir = UPLOAD_PATH . 'doctors/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

        $saved_files = [];
        foreach ($uploaded_files as $field => $file) {
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $filename = $field . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
            $destination = $upload_dir . $filename;
            
            if (move_uploaded_file($file['tmp_name'], $destination)) {
                $saved_files[$field] = 'uploads/doctors/' . $filename;
            }
        }

        $password_hash  = password_hash($password, PASSWORD_BCRYPT);
        $doc_license    = $saved_files['doc_license'] ?? null;
        $doc_qual       = $saved_files['doc_qualification'] ?? null;
        $doc_cnic       = $saved_files['doc_cnic'] ?? null;
        $profile_photo  = $saved_files['profile_photo'] ?? null;
        $spec_id        = $old['specialization'];
        $exp_years      = $old['experience'];
        $consult_fee    = $old['consultation_fee'];

        $stmt = $conn->prepare("
            INSERT INTO doctors (
                full_name, email, phone, gender, pmc_license_number, specialization_id,
                qualification, experience_years, consultation_fee, clinic_name, clinic_address,
                city, bio, password, doc_license, doc_qualification, doc_cnic, profile_photo,
                verification_status, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
        ");

        $stmt->bind_param('sssssisidsssssssss',
            $old['full_name'], $old['email'], $old['phone'], $old['gender'],
            $old['pmc_license'], $spec_id, $old['qualification'],
            $exp_years, $consult_fee, $old['clinic_name'],
            $old['clinic_address'], $old['city'], $old['bio'], $password_hash,
            $doc_license, $doc_qual, $doc_cnic, $profile_photo
        );

        if ($stmt->execute()) {
            $doctor_id = $conn->insert_id;
            
            // Send notification to admin
            $admin_notification = "New doctor registration: Dr. {$old['full_name']} ({$old['pmc_license']}) needs verification.";
            $notif_stmt = $conn->prepare("
                INSERT INTO notifications (user_type, user_id, title, message, type, channel)
                VALUES ('admin', 1, 'New Doctor Registration', ?, 'new_doctor_registration', 'in_app')
            ");
            $notif_stmt->bind_param('s', $admin_notification);
            $notif_stmt->execute();
            
            setFlash('success', '✅ Registration submit ho gaya! Admin verification ke baad aapka account activate hoga. 1-2 working days mein confirmation milega.');
            header('Location: ' . SITE_URL . '/doctor-login.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>Doctor 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">

<nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
    <div class="container">
        <a class="navbar-brand fw-bold text-primary" href="index.php">
            <i class="fas fa-heartbeat"></i> HealthLink
        </a>
        <div class="navbar-nav">
            <a class="nav-link" href="doctor-login.php">Already have account? Login</a>
        </div>
    </div>
</nav>

<div class="container mt-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card shadow">
                <div class="card-header bg-success text-white text-center">
                    <h4><i class="fas fa-user-md"></i> Doctor Registration</h4>
                    <p class="mb-0">Join HealthLink as a verified medical professional</p>
                </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" enctype="multipart/form-data">
                        <div class="row">
                            <div class="col-md-6 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="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>

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

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">PMC License Number *</label>
                                <input type="text" name="pmc_license" class="form-control" value="<?= htmlspecialchars($old['pmc_license'] ?? '') ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Specialization *</label>
                                <select name="specialization" class="form-select" required>
                                    <option value="">Select Specialization</option>
                                    <?php foreach ($specializations as $spec): ?>
                                        <option value="<?= $spec['id'] ?>" <?= ($old['specialization'] ?? 0) == $spec['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($spec['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Qualification *</label>
                                <input type="text" name="qualification" class="form-control" placeholder="MBBS, FCPS, MD, etc." value="<?= htmlspecialchars($old['qualification'] ?? '') ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Experience (Years) *</label>
                                <input type="number" name="experience" class="form-control" min="0" value="<?= $old['experience'] ?? '' ?>" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Consultation Fee (Rs.) *</label>
                                <input type="number" name="consultation_fee" class="form-control" min="100" value="<?= $old['consultation_fee'] ?? '' ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">City *</label>
                                <input type="text" name="city" class="form-control" value="<?= htmlspecialchars($old['city'] ?? '') ?>" required>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Clinic/Hospital Name</label>
                            <input type="text" name="clinic_name" class="form-control" value="<?= htmlspecialchars($old['clinic_name'] ?? '') ?>">
                        </div>

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

                        <div class="mb-3">
                            <label class="form-label">Professional Bio</label>
                            <textarea name="bio" class="form-control" rows="4" placeholder="Tell patients about your experience and expertise..."><?= htmlspecialchars($old['bio'] ?? '') ?></textarea>
                        </div>

                        <hr>
                        
                        <h6><i class="fas fa-upload"></i> Required Documents</h6>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">PMC License Document *</label>
                                <input type="file" name="doc_license" class="form-control" accept=".pdf,.jpg,.jpeg,.png" required>
                                <small class="text-muted">Upload PDF, JPG, or PNG</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Qualification Certificate *</label>
                                <input type="file" name="doc_qualification" class="form-control" accept=".pdf,.jpg,.jpeg,.png" required>
                                <small class="text-muted">Upload PDF, JPG, or PNG</small>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">CNIC Copy *</label>
                                <input type="file" name="doc_cnic" class="form-control" accept=".pdf,.jpg,.jpeg,.png" required>
                                <small class="text-muted">Upload PDF, JPG, or PNG</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Profile Photo (Optional)</label>
                                <input type="file" name="profile_photo" class="form-control" accept=".jpg,.jpeg,.png">
                                <small class="text-muted">Upload JPG or PNG</small>
                            </div>
                        </div>

                        <hr>

                        <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 8 characters, 1 uppercase, 1 number</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="alert alert-info">
                            <h6><i class="fas fa-info-circle"></i> Important Information:</h6>
                            <ul class="mb-0">
                                <li>Your account will be verified by admin within 1-2 working days</li>
                                <li>All uploaded documents should be clear and legible</li>
                                <li>You'll receive email notification once verification is complete</li>
                                <li>Only verified doctors can start consultations</li>
                            </ul>
                        </div>

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

                    <div class="text-center mt-3">
                        <p>Already registered? <a href="doctor-login.php">Login here</a></p>
                        <a href="index.php" class="text-muted">Back to Home</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>