<?php
require_once '../config.php';
requireDoctor();

$doctor_id = $_SESSION['doctor_id'];

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_personal') {
        $full_name       = clean($_POST['full_name'] ?? '');
        $phone           = clean($_POST['phone'] ?? '');
        $gender          = clean($_POST['gender'] ?? '');
        $qualification   = clean($_POST['qualification'] ?? '');
        $experience      = (int)($_POST['experience'] ?? 0);
        $consultation_fee= (float)($_POST['consultation_fee'] ?? 0);
        $specialization  = (int)($_POST['specialization'] ?? 0);
        $bio             = clean($_POST['bio'] ?? '');
        $clinic_name     = clean($_POST['clinic_name'] ?? '');
        $clinic_address  = clean($_POST['clinic_address'] ?? '');
        $city            = clean($_POST['city'] ?? '');

        // Handle profile photo upload
        $photo_sql = '';
        if (!empty($_FILES['profile_photo']['name'])) {
            $photo = uploadFile($_FILES['profile_photo'], 'doctors', ['jpg','jpeg','png']);
            if ($photo) $photo_sql = ", profile_photo = '$photo'";
        }

        $stmt = $conn->prepare("UPDATE doctors SET full_name=?, phone=?, gender=?, qualification=?, experience_years=?, consultation_fee=?, specialization_id=?, bio=?, clinic_name=?, clinic_address=?, city=? $photo_sql WHERE id=?");
        $stmt->bind_param('ssssiidsssi', $full_name, $phone, $gender, $qualification, $experience, $consultation_fee, $specialization, $bio, $clinic_name, $clinic_address, $city, $doctor_id);
        $stmt->execute();

        $_SESSION['doctor_name'] = $full_name;
        setFlash('success', 'Profile updated successfully.');
        header('Location: profile.php');
        exit;
    }

    if ($action === 'change_password') {
        $current = $_POST['current_password'] ?? '';
        $new     = $_POST['new_password'] ?? '';
        $confirm = $_POST['confirm_password'] ?? '';

        $stmt = $conn->prepare("SELECT password FROM doctors WHERE id=?");
        $stmt->bind_param('i', $doctor_id);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();

        if (!password_verify($current, $row['password'])) {
            setFlash('error', 'Current password is incorrect.');
        } elseif (strlen($new) < 8) {
            setFlash('error', 'New password must be at least 8 characters.');
        } elseif ($new !== $confirm) {
            setFlash('error', 'Passwords do not match.');
        } else {
            $hash = password_hash($new, PASSWORD_BCRYPT);
            $conn->query("UPDATE doctors SET password='$hash' WHERE id=$doctor_id");
            setFlash('success', 'Password changed successfully.');
        }
        header('Location: profile.php#security');
        exit;
    }
}

// Fetch doctor data
$stmt = $conn->prepare("SELECT d.*, s.name as specialization_name FROM doctors d LEFT JOIN specializations s ON d.specialization_id = s.id WHERE d.id = ?");
$stmt->bind_param('i', $doctor_id);
$stmt->execute();
$doctor = $stmt->get_result()->fetch_assoc();

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

$status_colors = ['approved' => 'success', 'pending' => 'warning', 'rejected' => 'danger'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Profile - HealthLink Doctor</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">
  <style>
    body { font-family: Inter, sans-serif; background: #f0f4ff; margin: 0; }
    .doc-body { padding: 20px 24px; }
    .doc-card { background:#fff; border:1px solid #e8edf8; border-radius:14px; overflow:hidden; box-shadow:0 2px 12px rgba(11,74,203,.07); }
    @media(max-width:768px) { .doc-body { padding: 12px; } }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<?php include 'topbar.php'; ?>

<div class="doc-main">
  <div class="doc-body">
    <?php displayFlash(); ?>

    <!-- Profile Header Card -->
    <div class="doc-card p-4 mb-4">
      <div class="d-flex align-items-center gap-4 flex-wrap">
        <?php if (!empty($doctor['profile_photo'])): ?>
          <img src="<?= SITE_URL ?>/<?= $doctor['profile_photo'] ?>" style="width:80px;height:80px;border-radius:50%;object-fit:cover;border:3px solid #e6f5f3;" alt="Photo">
        <?php else: ?>
          <div style="width:80px;height:80px;border-radius:50%;background:#e6f5f3;display:flex;align-items:center;justify-content:center;font-size:2.2rem;">👨⚕️</div>
        <?php endif; ?>
        <div>
          <h4 class="mb-1 fw-800">Dr. <?= htmlspecialchars($doctor['full_name']) ?></h4>
          <div style="font-size:0.85rem;color:#718096;">
            <?= htmlspecialchars($doctor['specialization_name'] ?? '') ?>
            &nbsp;·&nbsp; <?= htmlspecialchars($doctor['qualification']) ?>
            &nbsp;·&nbsp; <?= $doctor['experience_years'] ?> yrs exp
          </div>
          <div class="mt-2">
            <span class="badge bg-<?= $status_colors[$doctor['verification_status']] ?? 'secondary' ?>">
              <?= ucfirst($doctor['verification_status']) ?>
            </span>
            <span style="background:#e6f5f3;color:#0B7B6E;border-radius:20px;padding:3px 12px;font-size:0.75rem;font-weight:700;margin-left:6px;">
              Rs. <?= number_format($doctor['consultation_fee']) ?> / consultation
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- Tabs -->
    <ul class="nav nav-tabs mb-4" id="profileTabs">
      <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#personal"><i class="fas fa-user me-1"></i>Personal Info</a></li>
      <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#clinic"><i class="fas fa-hospital me-1"></i>Clinic Details</a></li>
      <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#documents"><i class="fas fa-file-alt me-1"></i>Documents</a></li>
      <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#security"><i class="fas fa-lock me-1"></i>Security</a></li>
    </ul>

    <div class="tab-content">

      <!-- Personal Info Tab -->
      <div class="tab-pane fade show active" id="personal">
        <div class="doc-card">
          <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-user me-2 text-primary"></i>Personal Information</h6></div>
          <div class="p-4">
            <form method="POST" enctype="multipart/form-data">
              <input type="hidden" name="action" value="update_personal">
              <div class="row g-3">
                <div class="col-md-12 mb-1">
                  <label class="form-label fw-600">Profile Photo</label>
                  <input type="file" name="profile_photo" class="form-control" accept="image/*">
                  <small class="text-muted">JPG or PNG, max 2MB</small>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600">Full Name *</label>
                  <input type="text" name="full_name" class="form-control" value="<?= htmlspecialchars($doctor['full_name']) ?>" required>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600">Phone *</label>
                  <input type="text" name="phone" class="form-control" value="<?= htmlspecialchars($doctor['phone']) ?>" required>
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Gender</label>
                  <select name="gender" class="form-select">
                    <option value="male"   <?= $doctor['gender']==='male'   ? 'selected' : '' ?>>Male</option>
                    <option value="female" <?= $doctor['gender']==='female' ? 'selected' : '' ?>>Female</option>
                  </select>
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Qualification</label>
                  <input type="text" name="qualification" class="form-control" value="<?= htmlspecialchars($doctor['qualification']) ?>" placeholder="MBBS, FCPS...">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Specialization</label>
                  <select name="specialization" class="form-select">
                    <?php foreach ($specializations as $sp): ?>
                      <option value="<?= $sp['id'] ?>" <?= $doctor['specialization_id']==$sp['id']?'selected':'' ?>><?= htmlspecialchars($sp['name']) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Experience (Years)</label>
                  <input type="number" name="experience" class="form-control" value="<?= $doctor['experience_years'] ?>" min="0">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Consultation Fee (Rs.)</label>
                  <input type="number" name="consultation_fee" class="form-control" value="<?= $doctor['consultation_fee'] ?>" min="0">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">City</label>
                  <input type="text" name="city" class="form-control" value="<?= htmlspecialchars($doctor['city'] ?? '') ?>">
                </div>
                <div class="col-md-12">
                  <label class="form-label fw-600">Professional Bio</label>
                  <textarea name="bio" class="form-control" rows="4" placeholder="Tell patients about your expertise..."><?= htmlspecialchars($doctor['bio'] ?? '') ?></textarea>
                </div>
              </div>
              <div class="mt-3">
                <button type="submit" class="btn btn-success"><i class="fas fa-save me-1"></i>Save Changes</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- Clinic Details Tab -->
      <div class="tab-pane fade" id="clinic">
        <div class="doc-card">
          <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-hospital me-2 text-info"></i>Clinic / Hospital Details</h6></div>
          <div class="p-4">
            <form method="POST">
              <input type="hidden" name="action" value="update_personal">
              <!-- Pass unchanged personal fields as hidden -->
              <input type="hidden" name="full_name"       value="<?= htmlspecialchars($doctor['full_name']) ?>">
              <input type="hidden" name="phone"           value="<?= htmlspecialchars($doctor['phone']) ?>">
              <input type="hidden" name="gender"          value="<?= htmlspecialchars($doctor['gender']) ?>">
              <input type="hidden" name="qualification"   value="<?= htmlspecialchars($doctor['qualification']) ?>">
              <input type="hidden" name="experience"      value="<?= $doctor['experience_years'] ?>">
              <input type="hidden" name="consultation_fee" value="<?= $doctor['consultation_fee'] ?>">
              <input type="hidden" name="specialization"  value="<?= $doctor['specialization_id'] ?>">
              <input type="hidden" name="bio"             value="<?= htmlspecialchars($doctor['bio'] ?? '') ?>">
              <div class="row g-3">
                <div class="col-md-6">
                  <label class="form-label fw-600">Clinic / Hospital Name</label>
                  <input type="text" name="clinic_name" class="form-control" value="<?= htmlspecialchars($doctor['clinic_name'] ?? '') ?>">
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600">City</label>
                  <input type="text" name="city" class="form-control" value="<?= htmlspecialchars($doctor['city'] ?? '') ?>">
                </div>
                <div class="col-md-12">
                  <label class="form-label fw-600">Clinic Address</label>
                  <textarea name="clinic_address" class="form-control" rows="3"><?= htmlspecialchars($doctor['clinic_address'] ?? '') ?></textarea>
                </div>
              </div>
              <div class="mt-3">
                <button type="submit" class="btn btn-info text-white"><i class="fas fa-save me-1"></i>Save Clinic Details</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- Documents Tab -->
      <div class="tab-pane fade" id="documents">
        <div class="doc-card">
          <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-file-alt me-2 text-warning"></i>Uploaded Documents</h6></div>
          <div class="p-4">
            <div class="row g-3">
              <?php $docs = [
                ['doc_license',       'fas fa-id-badge',      'PMC License',              'primary'],
                ['doc_qualification', 'fas fa-graduation-cap','Qualification Certificate', 'success'],
                ['doc_cnic',          'fas fa-id-card',       'CNIC Copy',                'info'],
              ]; ?>
              <?php foreach ($docs as [$field, $icon, $label, $color]): ?>
                <div class="col-md-4">
                  <div class="doc-card p-3 text-center" style="border-top: 4px solid var(--bs-<?= $color ?>);">
                    <i class="<?= $icon ?> fa-2x text-<?= $color ?> mb-2"></i>
                    <div class="fw-700 mb-2"><?= $label ?></div>
                    <?php if (!empty($doctor[$field])): ?>
                      <a href="<?= SITE_URL ?>/<?= $doctor[$field] ?>" target="_blank" class="btn btn-sm btn-outline-<?= $color ?>">
                        <i class="fas fa-eye me-1"></i>View Document
                      </a>
                      <div class="mt-1"><span class="badge bg-success" style="font-size:0.65rem;">✓ Uploaded</span></div>
                    <?php else: ?>
                      <span class="badge bg-secondary">Not uploaded</span>
                    <?php endif; ?>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>

            <div class="alert alert-info mt-4">
              <i class="fas fa-info-circle me-1"></i>
              To update documents, please contact admin support. Documents are verified manually.
            </div>

            <!-- Verification Status -->
            <div class="mt-3 p-3" style="background:#f7fafa;border-radius:12px;border:1px solid #e2e8f0;">
              <h6 class="fw-700">Verification Status</h6>
              <div class="d-flex align-items-center gap-3">
                <span class="badge bg-<?= $status_colors[$doctor['verification_status']] ?? 'secondary' ?> fs-6">
                  <?= ucfirst($doctor['verification_status']) ?>
                </span>
                <?php if ($doctor['verification_status'] === 'pending'): ?>
                  <span style="font-size:0.82rem;color:#718096;">Your documents are under review. You'll be notified once verified.</span>
                <?php elseif ($doctor['verification_status'] === 'approved'): ?>
                  <span style="font-size:0.82rem;color:#38a169;">✓ Your account is verified. You can receive patient consultations.</span>
                <?php else: ?>
                  <span style="font-size:0.82rem;color:#e53e3e;">Your application was rejected. Please contact admin for details.</span>
                <?php endif; ?>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Security Tab -->
      <div class="tab-pane fade" id="security">
        <div class="doc-card">
          <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-lock me-2 text-danger"></i>Change Password</h6></div>
          <div class="p-4">
            <form method="POST" style="max-width:420px;">
              <input type="hidden" name="action" value="change_password">
              <div class="mb-3">
                <label class="form-label fw-600">Current Password</label>
                <input type="password" name="current_password" class="form-control" required>
              </div>
              <div class="mb-3">
                <label class="form-label fw-600">New Password</label>
                <input type="password" name="new_password" class="form-control" required>
                <small class="text-muted">Minimum 8 characters</small>
              </div>
              <div class="mb-3">
                <label class="form-label fw-600">Confirm New Password</label>
                <input type="password" name="confirm_password" class="form-control" required>
              </div>
              <button type="submit" class="btn btn-danger"><i class="fas fa-key me-1"></i>Change Password</button>
            </form>
          </div>
        </div>
      </div>

    </div><!-- end tab-content -->
  </div><!-- end doc-body -->
</div><!-- end doc-main -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // Activate tab from URL hash
  const hash = window.location.hash;
  if (hash) {
    const tab = document.querySelector(`a[href="${hash}"]`);
    if (tab) new bootstrap.Tab(tab).show();
  }
</script>
</body>
</html>
