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

$patient_id = $_SESSION['patient_id'];
$errors = [];
$success = '';

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

    if ($action === 'update_personal') {
        $fields = ['full_name','phone','gender','date_of_birth','blood_group','address','city','state'];
        $values = [];
        foreach ($fields as $f) $values[$f] = clean($_POST[$f] ?? '');

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

        $stmt = $conn->prepare("UPDATE patients SET full_name=?, phone=?, gender=?, date_of_birth=?, blood_group=?, address=?, city=?, state=? $photo_sql WHERE id=?");
        $stmt->bind_param('ssssssssi', $values['full_name'], $values['phone'], $values['gender'],
            $values['date_of_birth'], $values['blood_group'], $values['address'], $values['city'], $values['state'], $patient_id);
        $stmt->execute();
        $_SESSION['patient_name'] = $values['full_name'];
        setFlash('success', 'Personal information updated successfully.');
        header('Location: profile.php');
        exit;
    }

    if ($action === 'update_medical') {
        $allergies       = clean($_POST['allergies'] ?? '');
        $chronic_diseases = clean($_POST['chronic_diseases'] ?? '');
        $current_medications = clean($_POST['current_medications'] ?? '');
        $medical_history = clean($_POST['medical_history'] ?? '');
        $family_history  = clean($_POST['family_history'] ?? '');
        $smoking         = clean($_POST['smoking'] ?? '');
        $alcohol         = clean($_POST['alcohol'] ?? '');
        $height          = clean($_POST['height'] ?? '');
        $weight          = clean($_POST['weight'] ?? '');

        $stmt = $conn->prepare("UPDATE patients SET allergies=?, chronic_diseases=?, current_medications=?, medical_history=?, family_history=?, smoking=?, alcohol=?, height=?, weight=? WHERE id=?");
        $stmt->bind_param('ssssssssi', $allergies, $chronic_diseases, $current_medications, $medical_history, $family_history, $smoking, $alcohol, $height, $weight, $patient_id);
        $stmt->execute();
        setFlash('success', 'Medical information updated successfully.');
        header('Location: profile.php#medical');
        exit;
    }

    if ($action === 'update_emergency') {
        $ec_name     = clean($_POST['emergency_contact_name'] ?? '');
        $ec_phone    = clean($_POST['emergency_contact_phone'] ?? '');
        $ec_relation = clean($_POST['emergency_contact_relation'] ?? '');

        $stmt = $conn->prepare("UPDATE patients SET emergency_contact_name=?, emergency_contact_phone=?, emergency_contact_relation=? WHERE id=?");
        $stmt->bind_param('sssi', $ec_name, $ec_phone, $ec_relation, $patient_id);
        $stmt->execute();
        setFlash('success', 'Emergency contact updated successfully.');
        header('Location: profile.php#emergency');
        exit;
    }

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

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

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

// Fetch patient data
$stmt = $conn->prepare("SELECT * FROM patients WHERE id = ?");
$stmt->bind_param('i', $patient_id);
$stmt->execute();
$p = $stmt->get_result()->fetch_assoc();
?>
<!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</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 { background: #f0f4ff; font-family: Inter, 'Segoe UI', sans-serif; }
    .card { border-radius: 14px; border: 1px solid #e2e8f0; box-shadow: 0 2px 8px rgba(11,74,203,0.07); }
    .nav-tabs .nav-link { color: #718096; font-weight: 500; }
    .nav-tabs .nav-link.active { color: #0B4ACB; border-bottom: 2px solid #0B4ACB; font-weight: 700; }
    .health-id-badge { background: #eff4ff; color: #0B4ACB; border-radius: 30px; padding: 5px 16px; font-size: 0.82rem; font-weight: 700; border: 1px solid #c7d7fc; }
    .profile-avatar { width: 90px; height: 90px; border-radius: 50%; object-fit: cover; border: 3px solid #c7d7fc; }
    .profile-avatar-placeholder { width: 90px; height: 90px; border-radius: 50%; background: #eff4ff; display: flex; align-items: center; justify-content: center; font-size: 2.5rem; border: 3px solid #0B4ACB; }
    .btn-primary-blue { background: linear-gradient(135deg,#0B4ACB,#3B63E6); color: #fff; border: none; padding: 9px 22px; border-radius: 10px; font-weight: 600; font-size: 13px; cursor: pointer; transition: all .2s; }
    .btn-primary-blue:hover { opacity: .9; transform: translateY(-1px); box-shadow: 0 4px 14px rgba(11,74,203,.3); }
    .top-bar {
      background: #fff; border-bottom: 1px solid #e2e8f0;
      padding: 14px 28px; display: flex; align-items: center;
      justify-content: flex-end;
      box-shadow: 0 1px 8px rgba(11,74,203,.07);
    }
    .top-bar h5 { margin: 0; font-size: 16px; font-weight: 700; color: #0f172a; }
    .page-body { padding: 26px 28px; }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>

<div class="main-content">
<?php $page_title = 'My Profile'; include 'topbar.php'; ?>

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

    <!-- Profile Header -->
    <div class="card mb-4 p-4">
      <div class="d-flex align-items-center gap-4 flex-wrap">
        <?php if (!empty($p['profile_photo'])): ?>
          <img src="<?= SITE_URL ?>/<?= $p['profile_photo'] ?>" class="profile-avatar" alt="Photo">
        <?php else: ?>
          <div class="profile-avatar-placeholder"><i class="fas fa-user" style="font-size:2rem;color:#0B4ACB;"></i></div>
        <?php endif; ?>
        <div>
          <h4 class="mb-1 fw-800"><?= htmlspecialchars($p['full_name']) ?></h4>
          <span class="health-id-badge me-2"><?= htmlspecialchars($p['health_id']) ?></span>
          <span class="badge bg-success">Active Patient</span>
          <div class="mt-2 text-muted" style="font-size:0.82rem;">
            <i class="fas fa-envelope me-1"></i><?= htmlspecialchars($p['email']) ?>
            &nbsp;|&nbsp;
            <i class="fas fa-phone me-1"></i><?= htmlspecialchars($p['phone']) ?>
            &nbsp;|&nbsp;
            <i class="fas fa-calendar me-1"></i>Joined <?= date('M Y', strtotime($p['created_at'])) ?>
          </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</a></li>
      <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#medical" id="medical-tab"><i class="fas fa-heartbeat me-1"></i>Medical Info</a></li>
      <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#emergency"><i class="fas fa-phone-alt me-1"></i>Emergency Contact</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 Information -->
      <div class="tab-pane fade show active" id="personal">
        <div class="card">
          <div class="card-header bg-white"><h6 class="mb-0 fw-700"><i class="fas fa-user me-2 text-primary"></i>Personal Information</h6></div>
          <div class="card-body">
            <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-2">
                  <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($p['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($p['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" <?= $p['gender']==='male'?'selected':'' ?>>Male</option>
                    <option value="female" <?= $p['gender']==='female'?'selected':'' ?>>Female</option>
                    <option value="other" <?= $p['gender']==='other'?'selected':'' ?>>Other</option>
                  </select>
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Date of Birth</label>
                  <input type="date" name="date_of_birth" class="form-control" value="<?= $p['date_of_birth'] ?>">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Blood Group</label>
                  <select name="blood_group" class="form-select">
                    <option value="">Select</option>
                    <?php foreach(['A+','A-','B+','B-','AB+','AB-','O+','O-'] as $bg): ?>
                      <option value="<?= $bg ?>" <?= $p['blood_group']===$bg?'selected':'' ?>><?= $bg ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="col-md-12">
                  <label class="form-label fw-600">Address</label>
                  <textarea name="address" class="form-control" rows="2"><?= htmlspecialchars($p['address'] ?? '') ?></textarea>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600">City</label>
                  <input type="text" name="city" class="form-control" value="<?= htmlspecialchars($p['city'] ?? '') ?>">
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600">State / Province</label>
                  <input type="text" name="state" class="form-control" value="<?= htmlspecialchars($p['state'] ?? '') ?>">
                </div>
              </div>
              <div class="mt-3">
                <button type="submit" class="btn-primary-blue"><i class="fas fa-save me-1"></i>Save Changes</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- Medical Information -->
      <div class="tab-pane fade" id="medical">
        <div class="card">
          <div class="card-header bg-white"><h6 class="mb-0 fw-700"><i class="fas fa-heartbeat me-2 text-danger"></i>Medical Information</h6></div>
          <div class="card-body">
            <form method="POST">
              <input type="hidden" name="action" value="update_medical">
              <div class="row g-3">
                <div class="col-md-6">
                  <label class="form-label fw-600"><i class="fas fa-exclamation-triangle me-1 text-warning"></i> Allergies</label>
                  <textarea name="allergies" class="form-control" rows="3" placeholder="e.g. Penicillin, Peanuts..."><?= htmlspecialchars($p['allergies'] ?? '') ?></textarea>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600"><i class="fas fa-hospital me-1 text-info"></i> Chronic Diseases</label>
                  <textarea name="chronic_diseases" class="form-control" rows="3" placeholder="e.g. Diabetes Type 2, Hypertension..."><?= htmlspecialchars($p['chronic_diseases'] ?? '') ?></textarea>
                </div>
                <div class="col-md-12">
                  <label class="form-label fw-600"><i class="fas fa-pills me-1 text-success"></i> Current Medications</label>
                  <textarea name="current_medications" class="form-control" rows="3" placeholder="List all current medications with doses..."><?= htmlspecialchars($p['current_medications'] ?? '') ?></textarea>
                </div>
                <div class="col-md-12">
                  <label class="form-label fw-600"><i class="fas fa-clipboard-list me-1 text-primary"></i> Medical History</label>
                  <textarea name="medical_history" class="form-control" rows="4" placeholder="Past surgeries, major illnesses, hospitalizations..."><?= htmlspecialchars($p['medical_history'] ?? '') ?></textarea>
                </div>
                <div class="col-md-12">
                  <label class="form-label fw-600"><i class="fas fa-users me-1 text-secondary"></i> Family Medical History</label>
                  <textarea name="family_history" class="form-control" rows="3" placeholder="Family history of diabetes, heart disease, cancer..."><?= htmlspecialchars($p['family_history'] ?? '') ?></textarea>
                </div>
                <div class="col-md-3">
                  <label class="form-label fw-600">Height (cm)</label>
                  <input type="number" name="height" class="form-control" value="<?= $p['height'] ?? '' ?>" placeholder="e.g. 170">
                </div>
                <div class="col-md-3">
                  <label class="form-label fw-600">Weight (kg)</label>
                  <input type="number" name="weight" class="form-control" value="<?= $p['weight'] ?? '' ?>" placeholder="e.g. 70">
                </div>
                <div class="col-md-3">
                  <label class="form-label fw-600">Smoking</label>
                  <select name="smoking" class="form-select">
                    <option value="no" <?= ($p['smoking']??'')==='no'?'selected':'' ?>>No</option>
                    <option value="yes" <?= ($p['smoking']??'')==='yes'?'selected':'' ?>>Yes</option>
                    <option value="former" <?= ($p['smoking']??'')==='former'?'selected':'' ?>>Former</option>
                  </select>
                </div>
                <div class="col-md-3">
                  <label class="form-label fw-600">Alcohol</label>
                  <select name="alcohol" class="form-select">
                    <option value="no" <?= ($p['alcohol']??'')==='no'?'selected':'' ?>>No</option>
                    <option value="occasional" <?= ($p['alcohol']??'')==='occasional'?'selected':'' ?>>Occasional</option>
                    <option value="regular" <?= ($p['alcohol']??'')==='regular'?'selected':'' ?>>Regular</option>
                  </select>
                </div>
              </div>
              <div class="mt-3">
                <button type="submit" class="btn-primary-blue"><i class="fas fa-save me-1"></i>Save Medical Info</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- Emergency Contact -->
      <div class="tab-pane fade" id="emergency">
        <div class="card">
          <div class="card-header bg-white"><h6 class="mb-0 fw-700"><i class="fas fa-phone-alt me-2 text-warning"></i>Emergency Contact</h6></div>
          <div class="card-body">
            <form method="POST">
              <input type="hidden" name="action" value="update_emergency">
              <div class="row g-3">
                <div class="col-md-4">
                  <label class="form-label fw-600">Contact Name</label>
                  <input type="text" name="emergency_contact_name" class="form-control" value="<?= htmlspecialchars($p['emergency_contact_name'] ?? '') ?>">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Contact Phone</label>
                  <input type="text" name="emergency_contact_phone" class="form-control" value="<?= htmlspecialchars($p['emergency_contact_phone'] ?? '') ?>">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Relationship</label>
                  <select name="emergency_contact_relation" class="form-select">
                    <option value="">Select</option>
                    <?php foreach(['Father','Mother','Spouse','Sibling','Child','Friend','Other'] as $rel): ?>
                      <option value="<?= $rel ?>" <?= ($p['emergency_contact_relation']??'')===$rel?'selected':'' ?>><?= $rel ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>
              <div class="mt-3">
                <button type="submit" class="btn-primary-blue"><i class="fas fa-save me-1"></i>Save Emergency Contact</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- Security -->
      <div class="tab-pane fade" id="security">
        <div class="card">
          <div class="card-header bg-white"><h6 class="mb-0 fw-700"><i class="fas fa-lock me-2 text-danger"></i>Change Password</h6></div>
          <div class="card-body">
            <form method="POST" style="max-width:400px;">
              <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>
              </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-primary-blue"><i class="fas fa-key me-1"></i>Change Password</button>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // Activate tab from 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>
