<?php
require_once 'config.php';

// -- Handle Patient Modal Login --
$p_errors = [];
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['patient_modal_login'])) {
    $p_email = clean($_POST['p_email'] ?? '');
    $p_pass  = $_POST['p_password'] ?? '';
    if (empty($p_email) || empty($p_pass)) {
        $p_errors[] = 'Email and password required.';
    } else {
        $s = $conn->prepare("SELECT id,full_name,email,password FROM patients WHERE email=?");
        $s->bind_param('s', $p_email);
        $s->execute();
        $pat = $s->get_result()->fetch_assoc();
        if ($pat && password_verify($p_pass, $pat['password'])) {
            $_SESSION['patient_id']    = $pat['id'];
            $_SESSION['patient_name']  = $pat['full_name'];
            $_SESSION['patient_email'] = $pat['email'];
            header('Location: ' . SITE_URL . '/patient/dashboard.php');
            exit;
        }
        $p_errors[] = 'Invalid email or password.';
    }
}

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

// -- Handle Doctor Register Modal --
$dr_errors = [];
$dr_old = [];
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['doctor_modal_register'])) {
    $dr_old['full_name']        = clean($_POST['dr_full_name'] ?? '');
    $dr_old['email']            = clean($_POST['dr_email'] ?? '');
    $dr_old['phone']            = clean($_POST['dr_phone'] ?? '');
    $dr_old['gender']           = clean($_POST['dr_gender'] ?? '');
    $dr_old['pmc_license']      = clean($_POST['dr_pmc'] ?? '');
    $dr_old['specialization']   = (int)($_POST['dr_specialization'] ?? 0);
    $dr_old['qualification']    = clean($_POST['dr_qualification'] ?? '');
    $dr_old['experience']       = (int)($_POST['dr_experience'] ?? 0);
    $dr_old['consultation_fee'] = (float)($_POST['dr_fee'] ?? 0);
    $dr_old['city']             = clean($_POST['dr_city'] ?? '');
    $dr_old['clinic_name']      = clean($_POST['dr_clinic'] ?? '');
    $dr_pass  = $_POST['dr_password'] ?? '';
    $dr_pass2 = $_POST['dr_password2'] ?? '';

    if (empty($dr_old['full_name']))                               $dr_errors[] = 'Full name is required.';
    if (!filter_var($dr_old['email'], FILTER_VALIDATE_EMAIL))      $dr_errors[] = 'Enter a valid email.';
    if (strlen($dr_old['phone']) < 10)                             $dr_errors[] = 'Enter a valid phone number.';
    if (empty($dr_old['pmc_license']))                             $dr_errors[] = 'PMC License Number is required.';
    if (empty($dr_old['specialization']))                          $dr_errors[] = 'Select a specialization.';
    if (empty($dr_old['qualification']))                           $dr_errors[] = 'Qualification is required.';
    if ($dr_old['consultation_fee'] <= 0)                          $dr_errors[] = 'Enter consultation fee.';
    if (strlen($dr_pass) < 8)                                      $dr_errors[] = 'Password must be at least 8 characters.';
    if (!preg_match('/[A-Z]/', $dr_pass))                          $dr_errors[] = 'Password needs at least 1 uppercase letter.';
    if (!preg_match('/[0-9]/', $dr_pass))                          $dr_errors[] = 'Password needs at least 1 number.';
    if ($dr_pass !== $dr_pass2)                                    $dr_errors[] = 'Passwords do not match.';

    $dr_files = [];
    foreach (['dr_doc_license'=>'PMC License doc','dr_doc_cnic'=>'CNIC copy'] as $fk => $flabel) {
        if (empty($_FILES[$fk]['name'])) {
            $dr_errors[] = $flabel . ' is required.';
        } else {
            $dr_files[$fk] = $_FILES[$fk];
        }
    }
    foreach (['dr_doc_qualification','dr_profile_photo'] as $fk) {
        if (!empty($_FILES[$fk]['name'])) $dr_files[$fk] = $_FILES[$fk];
    }

    if (empty($dr_errors)) {
        $chk = $conn->prepare("SELECT id FROM doctors WHERE email=? OR pmc_license_number=?");
        $chk->bind_param('ss', $dr_old['email'], $dr_old['pmc_license']); $chk->execute();
        if ($chk->get_result()->num_rows > 0) $dr_errors[] = 'Email or PMC license already registered.';
    }

    if (empty($dr_errors)) {
        $upload_dir = UPLOAD_PATH . 'doctors/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        $saved = [];
        foreach ($dr_files as $fk => $file) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            if (!in_array($ext, ['jpg','jpeg','png','pdf'])) continue;
            $fname = $fk . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
            if (move_uploaded_file($file['tmp_name'], $upload_dir . $fname)) {
                $saved[$fk] = 'uploads/doctors/' . $fname;
            }
        }
        $hash        = password_hash($dr_pass, PASSWORD_BCRYPT);
        $doc_lic     = $saved['dr_doc_license'] ?? null;
        $doc_qual    = $saved['dr_doc_qualification'] ?? null;
        $doc_cnic    = $saved['dr_doc_cnic'] ?? null;
        $photo       = $saved['dr_profile_photo'] ?? null;
        $spec_id     = $dr_old['specialization'];
        $exp         = $dr_old['experience'];
        $fee         = $dr_old['consultation_fee'];

        $ins = $conn->prepare("INSERT INTO doctors (full_name,email,phone,gender,pmc_license_number,specialization_id,qualification,experience_years,consultation_fee,clinic_name,city,password,doc_license,doc_qualification,doc_cnic,profile_photo,verification_status,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'pending',NOW())");
        $ins->bind_param('sssssisidssssss',
            $dr_old['full_name'], $dr_old['email'], $dr_old['phone'], $dr_old['gender'],
            $dr_old['pmc_license'], $spec_id, $dr_old['qualification'],
            $exp, $fee, $dr_old['clinic_name'], $dr_old['city'], $hash,
            $doc_lic, $doc_qual, $doc_cnic, $photo
        );
        if ($ins->execute()) {
            $notif = "New doctor: Dr. {$dr_old['full_name']} ({$dr_old['pmc_license']}) needs verification.";
            $n = $conn->prepare("INSERT INTO notifications (user_type,user_id,title,message,type,channel) VALUES ('admin',1,'New Doctor Registration',?,'new_doctor_registration','in_app')");
            $n->bind_param('s',$notif); $n->execute();
            $dr_success = true;
        } else {
            $dr_errors[] = 'Registration failed. Please try again.';
        }
    }
}

// -- Handle Patient Register Modal --
$r_errors = [];
$r_old = [];
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['patient_modal_register'])) {
    $r_old['full_name'] = clean($_POST['r_full_name'] ?? '');
    $r_old['email']     = clean($_POST['r_email'] ?? '');
    $r_old['phone']     = clean($_POST['r_phone'] ?? '');
    $r_old['gender']    = clean($_POST['r_gender'] ?? '');
    $r_old['dob']       = clean($_POST['r_dob'] ?? '');
    $r_pass  = $_POST['r_password'] ?? '';
    $r_pass2 = $_POST['r_password2'] ?? '';

    if (empty($r_old['full_name']))          $r_errors[] = 'Full name is required.';
    if (!filter_var($r_old['email'], FILTER_VALIDATE_EMAIL)) $r_errors[] = 'Enter a valid email.';
    if (strlen($r_old['phone']) < 10)        $r_errors[] = 'Enter a valid phone number.';
    if (empty($r_old['gender']))             $r_errors[] = 'Select your gender.';
    if (empty($r_old['dob']))                $r_errors[] = 'Date of birth is required.';
    if (strlen($r_pass) < 6)                 $r_errors[] = 'Password must be at least 6 characters.';
    if ($r_pass !== $r_pass2)                $r_errors[] = 'Passwords do not match.';

    if (empty($r_errors)) {
        $chk = $conn->prepare("SELECT id FROM patients WHERE email=?");
        $chk->bind_param('s', $r_old['email']); $chk->execute();
        if ($chk->get_result()->num_rows > 0) $r_errors[] = 'This email is already registered.';
    }
    if (empty($r_errors)) {
        $health_id = generateHealthId($conn);
        $hash = password_hash($r_pass, PASSWORD_BCRYPT);
        $ins = $conn->prepare("INSERT INTO patients (health_id,full_name,email,phone,gender,date_of_birth,password,created_at) VALUES (?,?,?,?,?,?,?,NOW())");
        $ins->bind_param('sssssss', $health_id, $r_old['full_name'], $r_old['email'], $r_old['phone'], $r_old['gender'], $r_old['dob'], $hash);
        if ($ins->execute()) {
            $_SESSION['patient_id']    = $conn->insert_id;
            $_SESSION['patient_name']  = $r_old['full_name'];
            $_SESSION['patient_email'] = $r_old['email'];
            $_SESSION['health_id']     = $health_id;
            header('Location: ' . SITE_URL . '/patient/dashboard.php'); exit;
        }
        $r_errors[] = 'Registration failed. Please try again.';
    }
}

// -- Handle Doctor Modal Login --
$d_errors = [];
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['doctor_modal_login'])) {
    $d_email = clean($_POST['d_email'] ?? '');
    $d_pass  = $_POST['d_password'] ?? '';
    if (empty($d_email) || empty($d_pass)) {
        $d_errors[] = 'Email and password required.';
    } else {
        $s = $conn->prepare("SELECT id,full_name,email,password,verification_status FROM doctors WHERE email=?");
        $s->bind_param('s', $d_email);
        $s->execute();
        $doc = $s->get_result()->fetch_assoc();
        if (!$doc) {
            $d_errors[] = 'No doctor account found with this email.';
        } elseif ($doc['verification_status'] !== 'approved') {
            $d_errors[] = 'Account pending admin verification.';
        } elseif (!password_verify($d_pass, $doc['password'])) {
            $d_errors[] = 'Invalid password.';
        } else {
            $_SESSION['doctor_id']    = $doc['id'];
            $_SESSION['doctor_name']  = $doc['full_name'];
            $_SESSION['doctor_email'] = $doc['email'];
            header('Location: ' . SITE_URL . '/doctor/dashboard.php');
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset
