<?php
// ============================================================
//  HealthLink – Doctor Registration
//  File: register-doctor.php
// ============================================================
require_once 'config.php';

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

$errors = [];
$old    = [];

// Specializations load karo
$specs = $conn->query("SELECT id, name, icon FROM specializations WHERE is_active = 1 ORDER BY name");

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['pmc_license']     = clean($_POST['pmc_license']      ?? '');
    $old['specialization']  = (int)($_POST['specialization']   ?? 0);
    $old['qualification']   = clean($_POST['qualification']    ?? '');
    $old['experience']      = (int)($_POST['experience']       ?? 0);
    $old['fee']             = (float)($_POST['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['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 upload validation
    $allowed_types = ['application/pdf', 'image/jpeg', 'image/png'];
    $max_size      = 3 * 1024 * 1024; // 3MB
    $uploaded_files = [];

    $file_fields = [
        'doc_license'       => 'PMC License Document',
        'doc_qualification' => 'Qualification Certificate',
        'doc_cnic'          => 'CNIC Copy',
        'profile_photo'     => 'Profile Photo',
    ];

    foreach ($file_fields as $field => $label) {
        if (!empty($_FILES[$field]['name'])) {
            $file = $_FILES[$field];
            if ($file['error'] !== UPLOAD_ERR_OK)         { $errors[] = "$label upload mein masla hua."; continue; }
            if ($file['size'] > $max_size)                 { $errors[] = "$label 3MB se chota hona chahiye."; continue; }
            if ($field === 'profile_photo') {
                if (!in_array($file['type'], ['image/jpeg','image/png'])) { $errors[] = "Profile photo sirf JPG/PNG hona chahiye."; continue; }
            } else {
                if (!in_array($file['type'], $allowed_types)) { $errors[] = "$label sirf PDF/JPG/PNG hona chahiye."; continue; }
            }
            $uploaded_files[$field] = $file;
        }
    }

    // Mandatory documents check
    foreach (['doc_license','doc_qualification','doc_cnic'] as $req) {
        if (empty($uploaded_files[$req])) {
            $errors[] = $file_fields[$req] . ' upload karna zaroor hai.';
        }
    }

    // Duplicate check
    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 (empty($errors)) {

        // Files save karo
        $upload_dir = UPLOAD_PATH . 'doctors/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

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

        $password_hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
        $doc_lic  = $saved_paths['doc_license']       ?? null;
        $doc_qual = $saved_paths['doc_qualification']  ?? null;
        $doc_cnic = $saved_paths['doc_cnic']           ?? null;
        $doc_photo= $saved_paths['profile_photo']      ?? null;

        $stmt = $conn->prepare("
            INSERT INTO doctors
              (full_name, email, phone, password, gender,
               pmc_license_number, specialization_id, qualification,
               experience_years, consultation_fee,
               clinic_name, clinic_address, city, bio,
               doc_license, doc_qualification, doc_cnic, profile_photo,
               verification_status)
            VALUES
              (?,?,?,?,?,  ?,?,?,?,?,  ?,?,?,?,  ?,?,?,?,  'pending')
        ");
        $stmt->bind_param(
            'ssssss ididssssssss',
            $old['full_name'], $old['email'], $old['phone'], $password_hash, $old['gender'],
            $old['pmc_license'], $old['specialization'], $old['qualification'],
            $old['experience'], $old['fee'],
            $old['clinic_name'], $old['clinic_address'], $old['city'], $old['bio'],
            $doc_lic, $doc_qual, $doc_cnic, $doc_photo
        );

        // Fix bind_param type string
        $stmt->close();

        // Clean bind
        $stmt2 = $conn->prepare("
            INSERT INTO doctors
              (full_name,email,phone,password,gender,
               pmc_license_number,specialization_id,qualification,
               experience_years,consultation_fee,
               clinic_name,clinic_address,city,bio,
               doc_license,doc_qualification,doc_cnic,profile_photo)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        ");
        $stmt2->bind_param(
            'ssssssssidssssssss',
            $old['full_name'], $old['email'], $old['phone'], $password_hash, $old['gender'],
            $old['pmc_license'], $old['specialization'], $old['qualification'],
            $old['experience'], $old['fee'],
            $old['clinic_name'], $old['clinic_address'], $old['city'], $old['bio'],
            $doc_lic, $doc_qual, $doc_cnic, $doc_photo
        );

        if ($stmt2->execute()) {
            $doctor_id = $conn->insert_id;
            $stmt2->close();

            // Audit log
            $action = 'doctor_registered';
            $ip     = $_SERVER['REMOTE_ADDR'] ?? '';
            $log    = $conn->prepare("INSERT INTO audit_logs (user_type,user_id,action,ip_address) VALUES ('doctor',?,?,?)");
            $log->bind_param('iss', $doctor_id, $action, $ip);
            $log->execute();

            // Admin ko notify karo
            $notif_msg = "Naya doctor registration: {$old['full_name']} ({$old['pmc_license']}) — verification pending.";
            $notif_type = 'new_doctor_registration';
            $notif_subj = 'New Doctor Registration — Action Required';
            $n = $conn->prepare("INSERT INTO notifications (user_type,user_id,channel,type,subject,message) VALUES ('admin',1,'email',?,?,?)");
            $n->bind_param('sss', $notif_type, $notif_subj, $notif_msg);
            $n->execute();

            setFlash('success', '✅ Registration submit ho gaya! Admin verification ke baad aapka account activate hoga. 1-2 working days mein.');
            header('Location: ' . SITE_URL . '/doctor-login.php');
            exit;
        } else {
            $errors[] = 'Database error: ' . $conn->error;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Doctor Registration – HealthLink</title>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <style>
    *, *::before, *::after { box-sizing:border-box; margin:0; padding:0; }
    :root {
      --teal:#0B7B6E; --teal-light:#13A898; --teal-pale:#E6F5F3;
      --navy:#0D2340; --slate:#4A5568; --border:#D4E8E5;
      --bg:#F7FAFA; --red:#e74c3c; --gold:#C8973A;
    }
    body { font-family:'Plus Jakarta Sans',sans-serif; background:var(--bg); color:var(--navy); }

    /* TOP HEADER */
    .top-bar {
      background:white; border-bottom:1px solid var(--border);
      padding:16px 5vw; display:flex; align-items:center; justify-content:space-between;
      position:sticky; top:0; z-index:50;
    }
    .brand { display:flex; align-items:center; gap:10px; text-decoration:none; }
    .brand-icon { width:38px; height:38px; border-radius:10px; background:linear-gradient(135deg,var(--teal),var(--teal-light)); display:flex; align-items:center; justify-content:center; font-size:1.2rem; }
    .brand-name { font-size:1.1rem; font-weight:800; color:var(--navy); }
    .brand-name span { color:var(--teal); }
    .login-link { font-size:0.85rem; color:var(--teal); text-decoration:none; font-weight:600; }

    /* HERO STRIP */
    .hero-strip {
      background: linear-gradient(135deg, var(--navy) 0%, #0B4A42 100%);
      padding: 48px 5vw; text-align:center; color:white;
    }
    .hero-strip h1 { font-size:clamp(1.6rem,3vw,2.2rem); font-weight:800; margin-bottom:10px; }
    .hero-strip p  { color:rgba(255,255,255,0.65); font-size:0.95rem; max-width:560px; margin:0 auto 24px; line-height:1.7; }
    .steps-strip { display:flex; justify-content:center; gap:32px; flex-wrap:wrap; }
    .step-chip {
      background:rgba(255,255,255,0.08); border:1px solid rgba(255,255,255,0.15);
      border-radius:40px; padding:8px 18px; font-size:0.8rem; color:rgba(255,255,255,0.8);
      display:flex; align-items:center; gap:8px;
    }

    /* MAIN FORM */
    .form-container { max-width:780px; margin:40px auto; padding:0 20px 60px; }

    .card {
      background:white; border-radius:16px; padding:32px 36px;
      border:1px solid var(--border); margin-bottom:24px;
    }
    .card-title {
      font-size:0.78rem; font-weight:700; text-transform:uppercase;
      letter-spacing:0.08em; color:var(--teal); margin-bottom:22px;
      display:flex; align-items:center; gap:8px;
    }

    .form-grid { display:grid; grid-template-columns:1fr 1fr; gap:16px; }
    .full { grid-column:1/-1; }

    .field { display:flex; flex-direction:column; gap:6px; }
    .field label { font-size:0.82rem; font-weight:600; color:var(--slate); }
    .field label .req { color:var(--red); margin-left:2px; }
    .field input, .field select, .field textarea {
      padding:11px 14px; border:1.5px solid var(--border); border-radius:9px;
      font-size:0.9rem; font-family:inherit; color:var(--navy); background:white;
      outline:none; transition:border 0.2s;
    }
    .field textarea { resize:vertical; min-height:90px; }
    .field input:focus, .field select:focus, .field textarea:focus {
      border-color:var(--teal); box-shadow:0 0 0 3px var(--teal-pale);
    }

    /* FILE UPLOAD */
    .file-field { display:flex; flex-direction:column; gap:6px; }
    .file-field label { font-size:0.82rem; font-weight:600; color:var(--slate); }
    .file-field label .req { color:var(--red); margin-left:2px; }
    .file-field .hint { font-size:0.72rem; color:var(--slate); }
    .file-drop {
      border:2px dashed var(--border); border-radius:10px;
      padding:20px; text-align:center; cursor:pointer;
      transition:all 0.2s; background:var(--bg);
    }
    .file-drop:hover { border-color:var(--teal); background:var(--teal-pale); }
    .file-drop input[type=file] { display:none; }
    .file-drop .icon { font-size:1.8rem; margin-bottom:6px; }
    .file-drop p { font-size:0.8rem; color:var(--slate); }
    .file-drop .selected { color:var(--teal); font-weight:600; font-size:0.82rem; margin-top:6px; display:none; }

    /* ERROR BOX */
    .error-box { background:#fdf2f2; border:1px solid #f5c6c6; border-radius:10px; padding:16px 20px; margin-bottom:24px; }
    .error-box p { color:var(--red); font-size:0.85rem; margin-bottom:4px; }
    .error-box p:last-child { margin:0; }
    .error-box p::before { content:'⚠ '; }

    /* NOTICE */
    .notice-box { background:#fffbf0; border:1px solid #f0d080; border-radius:10px; padding:16px 20px; margin-bottom:24px; font-size:0.85rem; color:#7a5c00; line-height:1.7; }

    /* TERMS */
    .terms-row { display:flex; align-items:flex-start; gap:10px; font-size:0.82rem; color:var(--slate); line-height:1.6; margin-bottom:20px; }
    .terms-row input { width:16px; height:16px; margin-top:2px; accent-color:var(--teal); flex-shrink:0; }
    .terms-row a { color:var(--teal); font-weight:600; text-decoration:none; }

    .btn-submit {
      width:100%; padding:15px; background:var(--teal); color:white;
      border:none; border-radius:10px; font-size:1rem; font-weight:700;
      cursor:pointer; font-family:inherit; transition:all 0.2s;
    }
    .btn-submit:hover { background:var(--teal-light); transform:translateY(-1px); }

    /* PASSWORD STRENGTH */
    .pw-bar { height:4px; border-radius:4px; background:var(--border); margin-top:6px; }
    .pw-fill { height:100%; border-radius:4px; transition:all 0.3s; width:0%; }

    @media(max-width:640px) {
      .form-grid { grid-template-columns:1fr; }
      .full { grid-column:1; }
      .card { padding:22px 18px; }
    }
  </style>
</head>
<body>

<!-- TOP BAR -->
<div class="top-bar">
  <a href="<?= SITE_URL ?>" class="brand">
    <div class="brand-icon">➕</div>
    <span class="brand-name">Health<span>Link</span></span>
  </a>
  <a href="<?= SITE_URL ?>/doctor-login.php" class="login-link">Pehle se registered? Login →</a>
</div>

<!-- HERO -->
<div class="hero-strip">
  <h1>🩺 Doctor Registration</h1>
  <p>HealthLink ke saath judain. Apni clinic online le aaein aur hazaron patients tak pounchaein.</p>
  <div class="steps-strip">
    <div class="step-chip">✅ Form Submit Karo</div>
    <div class="step-chip">🔍 Admin Verification (1-2 din)</div>
    <div class="step-chip">🎉 Account Activate — Patients Dekho</div>
  </div>
</div>

<!-- FORM -->
<div class="form-container">

  <?php if (!empty($errors)): ?>
    <div class="error-box">
      <?php foreach ($errors as $e): ?>
        <p><?= htmlspecialchars($e) ?></p>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>

  <div class="notice-box">
    ⚠️ <strong>Zaroori baat:</strong> Registration ke baad aapka account directly active nahi hoga. Admin team aapke PMC License aur documents verify karegi. Approval ke baad aapko email notification milega.
  </div>

  <form method="POST" enctype="multipart/form-data" novalidate>

    <!-- PERSONAL INFO -->
    <div class="card">
      <div class="card-title">👤 Personal Information</div>
      <div class="form-grid">
        <div class="field full">
          <label>Full Name (MBBS ke saath) <span class="req">*</span></label>
          <input type="text" name="full_name" placeholder="Dr. Muhammad Ahmed Khan" value="<?= htmlspecialchars($old['full_name'] ?? '') ?>" required>
        </div>
        <div class="field">
          <label>Email Address <span class="req">*</span></label>
          <input type="email" name="email" placeholder="doctor@email.com" value="<?= htmlspecialchars($old['email'] ?? '') ?>" required>
        </div>
        <div class="field">
          <label>Phone Number <span class="req">*</span></label>
          <input type="tel" name="phone" placeholder="03XX-XXXXXXX" value="<?= htmlspecialchars($old['phone'] ?? '') ?>" required>
        </div>
        <div class="field">
          <label>Gender</label>
          <select name="gender">
            <option value="">-- Select --</option>
            <option value="male"   <?= ($old['gender'] ?? '') === 'male'   ? 'selected':'' ?>>Male</option>
            <option value="female" <?= ($old['gender'] ?? '') === 'female' ? 'selected':'' ?>>Female</option>
          </select>
        </div>
      </div>
    </div>

    <!-- PROFESSIONAL INFO -->
    <div class="card">
      <div class="card-title">🏥 Professional Information</div>
      <div class="form-grid">
        <div class="field">
          <label>PMC License Number <span class="req">*</span></label>
          <input type="text" name="pmc_license" placeholder="PMC-XXXXX" value="<?= htmlspecialchars($old['pmc_license'] ?? '') ?>" required>
        </div>
        <div class="field">
          <label>Specialization <span class="req">*</span></label>
          <select name="specialization" required>
            <option value="">-- Select Specialization --</option>
            <?php while ($row = $specs->fetch_assoc()): ?>
              <option value="<?= $row['id'] ?>" <?= ($old['specialization'] ?? 0) == $row['id'] ? 'selected':'' ?>>
                <?= $row['icon'] ?> <?= htmlspecialchars($row['name']) ?>
              </option>
            <?php endwhile; ?>
          </select>
        </div>
        <div class="field">
          <label>Qualification <span class="req">*</span></label>
          <input type="text" name="qualification" placeholder="MBBS, FCPS, MRCP..." value="<?= htmlspecialchars($old['qualification'] ?? '') ?>" required>
        </div>
        <div class="field">
          <label>Experience (Years) <span class="req">*</span></label>
          <input type="number" name="experience" min="0" max="60" placeholder="5" value="<?= htmlspecialchars($old['experience'] ?? '') ?>" required>
        </div>
        <div class="field">
          <label>Consultation Fee (PKR) <span class="req">*</span></label>
          <input type="number" name="fee" min="1" step="50" placeholder="800" value="<?= htmlspecialchars($old['fee'] ?? '') ?>" required>
        </div>
        <div class="field full">
          <label>Professional Bio</label>
          <textarea name="bio" placeholder="Apne baare mein likhein — experience, specialties, approach..."><?= htmlspecialchars($old['bio'] ?? '') ?></textarea>
        </div>
      </div>
    </div>

    <!-- CLINIC INFO -->
    <div class="card">
      <div class="card-title">🏢 Clinic / Hospital Information</div>
      <div class="form-grid">
        <div class="field full">
          <label>Clinic / Hospital Name</label>
          <input type="text" name="clinic_name" placeholder="Al-Shifa Clinic, Islamabad" value="<?= htmlspecialchars($old['clinic_name'] ?? '') ?>">
        </div>
        <div class="field">
          <label>City</label>
          <input type="text" name="city" placeholder="Islamabad" value="<?= htmlspecialchars($old['city'] ?? '') ?>">
        </div>
        <div class="field">
          <label>Clinic Address</label>
          <input type="text" name="clinic_address" placeholder="Street / Area" value="<?= htmlspecialchars($old['clinic_address'] ?? '') ?>">
        </div>
      </div>
    </div>

    <!-- DOCUMENTS -->
    <div class="card">
      <div class="card-title">📄 Documents Upload</div>
      <div class="form-grid">

        <div class="file-field">
          <label>PMC License Document <span class="req">*</span></label>
          <span class="hint">PDF / JPG / PNG — max 3MB</span>
          <div class="file-drop" onclick="document.getElementById('doc_license').click()">
            <input type="file" id="doc_license" name="doc_license" accept=".pdf,.jpg,.jpeg,.png" onchange="showFile(this,'sel_lic')">
            <div class="icon">📜</div>
            <p>Click karke file chunein</p>
            <p class="selected" id="sel_lic"></p>
          </div>
        </div>

        <div class="file-field">
          <label>Qualification Certificate <span class="req">*</span></label>
          <span class="hint">MBBS/FCPS degree scan — max 3MB</span>
          <div class="file-drop" onclick="document.getElementById('doc_qual').click()">
            <input type="file" id="doc_qual" name="doc_qualification" accept=".pdf,.jpg,.jpeg,.png" onchange="showFile(this,'sel_qual')">
            <div class="icon">🎓</div>
            <p>Click karke file chunein</p>
            <p class="selected" id="sel_qual"></p>
          </div>
        </div>

        <div class="file-field">
          <label>CNIC Copy <span class="req">*</span></label>
          <span class="hint">Front side — max 3MB</span>
          <div class="file-drop" onclick="document.getElementById('doc_cnic').click()">
            <input type="file" id="doc_cnic" name="doc_cnic" accept=".pdf,.jpg,.jpeg,.png" onchange="showFile(this,'sel_cnic')">
            <div class="icon">🪪</div>
            <p>Click karke file chunein</p>
            <p class="selected" id="sel_cnic"></p>
          </div>
        </div>

        <div class="file-field">
          <label>Profile Photo</label>
          <span class="hint">Professional photo — JPG/PNG, max 3MB</span>
          <div class="file-drop" onclick="document.getElementById('profile_photo').click()">
            <input type="file" id="profile_photo" name="profile_photo" accept=".jpg,.jpeg,.png" onchange="showFile(this,'sel_photo')">
            <div class="icon">📸</div>
            <p>Click karke photo chunein</p>
            <p class="selected" id="sel_photo"></p>
          </div>
        </div>

      </div>
    </div>

    <!-- PASSWORD -->
    <div class="card">
      <div class="card-title">🔐 Password Setup</div>
      <div class="form-grid">
        <div class="field">
          <label>Password <span class="req">*</span></label>
          <input type="password" name="password" id="pw" placeholder="Min 8 chars, 1 capital, 1 number" required>
          <div class="pw-bar"><div class="pw-fill" id="pwFill"></div></div>
        </div>
        <div class="field">
          <label>Confirm Password <span class="req">*</span></label>
          <input type="password" name="confirm_password" placeholder="Dobara likhao" required>
        </div>
      </div>
    </div>

    <!-- SUBMIT -->
    <div class="terms-row">
      <input type="checkbox" id="terms" name="terms" required>
      <label for="terms">
        Main tasdeeq karta/karti hun ke mere documents authentic hain aur main
        <a href="<?= SITE_URL ?>/terms.php" target="_blank">Terms & Conditions</a> se mutafiq hun.
        Ghalat documents submit karna account ban ki wajah ban sakta hai.
      </label>
    </div>

    <button type="submit" class="btn-submit">📋 Registration Submit Karein</button>

  </form>
</div>

<script>
function showFile(input, targetId) {
  const el = document.getElementById(targetId);
  if (input.files.length > 0) {
    el.textContent = '✓ ' + input.files[0].name;
    el.style.display = 'block';
  }
}

// Password strength
const pw = document.getElementById('pw');
const fill = document.getElementById('pwFill');
pw.addEventListener('input', () => {
  const v = pw.value;
  let s = 0;
  if (v.length >= 8)           s++;
  if (/[A-Z]/.test(v))         s++;
  if (/[0-9]/.test(v))         s++;
  if (/[^A-Za-z0-9]/.test(v)) s++;
  const colors = ['#e74c3c','#e74c3c','#f39c12','#27ae60','#0B7B6E'];
  fill.style.width = (s * 25) + '%';
  fill.style.background = colors[s];
});
</script>
</body>
</html>