<?php
// /user/user_profile.php
require_once __DIR__ . '/_user_auth.php';
require_once __DIR__ . '/_user_layout.php';

if (!function_exists('h')) {
  function h($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
}

/* ---------------- CSRF (basic) ---------------- */
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$CSRF = $_SESSION['csrf'];

/* ---------------- Flash ---------------- */
$ok = $err = '';

/* ---------------- Handle Update Profile (POST) ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') === 'update_profile'
    && hash_equals($CSRF, $_POST['csrf'] ?? '')
) {
  $email          = trim($_POST['email'] ?? '');
  $contact_number = trim($_POST['contact_number'] ?? '');
  $address        = trim($_POST['address'] ?? '');
  $father_number  = trim($_POST['father_number'] ?? '');

  // Validation
  if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $err = 'Please enter a valid email address.';
  } elseif ($contact_number !== '' && !preg_match('/^0[0-9]{3}-?[0-9]{7}$/', $contact_number)) {
    $err = 'Contact number format is invalid (e.g. 03xx-xxxxxxx).';
  } elseif ($father_number !== '' && !preg_match('/^0[0-9]{3}-?[0-9]{7}$/', $father_number)) {
    $err = 'Father’s number format is invalid (e.g. 03xx-xxxxxxx).';
  } else {
    // Load current row
    $curQ = mysqli_query($conn, "SELECT email, contact_number, address, father_number FROM students WHERE id={$student_id} LIMIT 1");
    $cur  = mysqli_fetch_assoc($curQ) ?: ['email'=>'','contact_number'=>'','address'=>'','father_number'=>''];

    $newEmail   = ($email === '')          ? $cur['email']          : $email;
    $newContact = ($contact_number === '') ? $cur['contact_number'] : $contact_number;
    $newAddress = ($address === '')        ? $cur['address']        : $address;
    $newFather  = ($father_number === '')  ? $cur['father_number']  : $father_number;

    if ($newEmail === $cur['email'] && $newContact === $cur['contact_number']
        && $newAddress === $cur['address'] && $newFather === $cur['father_number']) {
      $ok = 'No changes detected.';
    } else {
      $st = mysqli_prepare($conn, "UPDATE students SET email=?, contact_number=?, address=?, father_number=? WHERE id=?");
      if (!$st) {
        $err = "Prepare failed: " . mysqli_error($conn);
      } else {
        mysqli_stmt_bind_param($st, "ssssi", $newEmail, $newContact, $newAddress, $newFather, $student_id);
        if (!mysqli_stmt_execute($st)) {
          $err = "Execute failed: " . mysqli_stmt_error($st);
        } else {
          $ok = 'Profile updated successfully.';
        }
        mysqli_stmt_close($st);
      }
    }
  }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // CSRF fail or unknown action
  $err = 'Invalid request. Please reload and try again.';
}

/* ---------------- Load Profile ---------------- */
$stu_q = mysqli_query($conn, "
  SELECT id, full_name, father_name, father_number, cnic, dob,
         contact_number, email, address,
         CASE WHEN EXISTS(
           SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
           WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='students' AND COLUMN_NAME='gender'
         ) THEN gender ELSE NULL END AS gender
  FROM students
  WHERE id={$student_id}
  LIMIT 1
");
$me_full = mysqli_fetch_assoc($stu_q);

// Make sure we never get “undefined variable” warnings
if (!$me_full) {
  $me_full = [
    'id' => $student_id,
    'full_name' => $_SESSION['student_name'] ?? 'Student',
    'father_name' => '',
    'father_number' => '',
    'cnic' => '',
    'dob' => '',
    'contact_number' => '',
    'email' => '',
    'address' => '',
    'gender' => '',
  ];
}

/* ---------------- Latest Registration ---------------- */
$reg_q = mysqli_query($conn, "
  SELECT r.id, r.reg_no, r.status AS reg_status, r.fee_status, r.approved_at,
         c.id AS course_id, c.name AS course, c.fee_type, c.course_fee, c.monthly_fee, c.duration_months,
         b.id AS batch_id, b.name AS batch, b.start_date, b.end_date,
         ts.name AS slot_name, ts.days, ts.start_time, ts.end_time
  FROM registrations r
  JOIN courses c  ON c.id=r.course_id
  LEFT JOIN batches b ON b.id=r.batch_id
  LEFT JOIN time_slots ts ON ts.id=b.time_slot_id
  WHERE r.student_id={$student_id}
  ORDER BY r.approved_at DESC
  LIMIT 1
");
$cur = mysqli_fetch_assoc($reg_q);

/* ---------------- Live fee summary (if any) ---------------- */
$fs = null;
if ($cur) {
  $fp_q = mysqli_query($conn, "
    SELECT fp.*
    FROM fee_payments fp
    WHERE fp.student_id={$student_id} AND fp.course_id=".(int)$cur['course_id']."
    ORDER BY fp.updated_at DESC
    LIMIT 1
  ");
  $fs = mysqli_fetch_assoc($fp_q);
}

/* ---------------- Registrations history ---------------- */
$regs = mysqli_query($conn, "
  SELECT r.reg_no, r.status, r.fee_status, r.approved_at,
         c.name AS course, b.name AS batch, b.start_date
  FROM registrations r
  JOIN courses c ON c.id=r.course_id
  LEFT JOIN batches b ON b.id=r.batch_id
  WHERE r.student_id={$student_id}
  ORDER BY r.approved_at DESC
");

/* ---------------- Render ---------------- */
user_header('My Profile');
?>

<!-- Bootstrap (scoped safely under .upx-profile) -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
/* ========= SCOPED styles (won’t affect layout) ========= */
.upx-profile * { box-sizing: border-box; }
.upx-profile .hero {
  background: linear-gradient(135deg, #e0eaff, #ffffff);
  border: 1px solid #dbeafe;
  border-radius: 14px;
  padding: 16px;
  display: flex; align-items: center; gap: 14px;
}
.upx-profile .avatar {
  width: 58px; height: 58px; border-radius: 999px;
  background: #2563eb; color:#fff; display:flex; align-items:center; justify-content:center;
  font-weight: 800; font-size: 20px; box-shadow: 0 8px 24px rgba(37,99,235,.25);
}
.upx-profile .pill {
  padding: 2px 8px; border:1px solid #bfdbfe; background:#dbeafe; color:#1e40af; border-radius:999px; font-size:12px; font-weight:700;
}
.upx-profile .info-item{ background:#fff; border:1px solid #e5e7eb; border-radius:10px; padding:10px }
.upx-profile .kpi { text-align:center; background:#fff; border:1px solid #e5e7eb; border-radius:12px; padding:16px }
.upx-profile .kpi .label{font-size:12px;color:#64748b}
.upx-profile .kpi .val{margin-top:6px;font-size:22px;font-weight:800}
.upx-profile .badge-ok {background:#dcfce7;color:#166534;border:1px solid #86efac;border-radius:999px;padding:.15rem .5rem;font-weight:700;font-size:12px}
.upx-profile .badge-warn {background:#fff7ed;color:#9a3412;border:1px solid #fed7aa;border-radius:999px;padding:.15rem .5rem;font-weight:700;font-size:12px}
.upx-profile .badge-danger {background:#fee2e2;color:#991b1b;border:1px solid #fecaca;border-radius:999px;padding:.15rem .5rem;font-weight:700;font-size:12px}
.upx-profile .section-title { color:#1e40af; display:flex; align-items:center; gap:.5rem; margin-bottom:.75rem }
.upx-profile .muted { color:#64748b; }
</style>

<div class="upx-profile">
  <div class="container-xxl px-0">

    <!-- HERO -->
    <div class="hero mb-3">
      <div class="avatar"><?= strtoupper(substr($me_full['full_name'] ?? 'S',0,1)) ?></div>
      <div class="flex-grow-1">
        <div class="fw-bold fs-5 text-dark mb-1"><?= h($me_full['full_name']) ?></div>
        <div class="muted">
          CNIC: <?= h($me_full['cnic'] ?: '-') ?>
          <span class="mx-1">•</span>
          Email: <?= h($me_full['email'] ?: '-') ?>
        </div>
      </div>
      <div>
        <button class="btn btn-outline-primary btn-sm" id="editToggle">
          <i class="fa-regular fa-pen-to-square me-1"></i> Edit Profile
        </button>
      </div>
    </div>

    <!-- Alerts -->
    <?php if($ok): ?>
      <div class="alert alert-success py-2"><?= h($ok) ?></div>
    <?php endif; ?>
    <?php if($err): ?>
      <div class="alert alert-danger py-2"><?= h($err) ?></div>
    <?php endif; ?>

    <!-- Personal Info -->
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h5 class="section-title mb-3">
          <i class="fa-regular fa-id-card"></i> Personal Information
          <span class="pill ms-2">Read Only</span>
        </h5>
        <div class="row g-2">
          <div class="col-md-6"><div class="info-item"><div class="text-muted small">Full Name</div><div><?= h($me_full['full_name']) ?></div></div></div>
          <div class="col-md-6"><div class="info-item"><div class="text-muted small">Father’s Name</div><div><?= h($me_full['father_name'] ?: '-') ?></div></div></div>
          <div class="col-md-6"><div class="info-item"><div class="text-muted small">Father’s Number</div><div><?= h($me_full['father_number'] ?: '-') ?></div></div></div>
          <div class="col-md-6"><div class="info-item"><div class="text-muted small">CNIC / B-Form</div><div><?= h($me_full['cnic'] ?: '-') ?></div></div></div>
          <div class="col-md-6"><div class="info-item"><div class="text-muted small">Date of Birth</div><div><?= h($me_full['dob'] ?: '-') ?></div></div></div>
          <div class="col-md-6"><div class="info-item"><div class="text-muted small">Gender</div><div><?= h($me_full['gender'] ?: '-') ?></div></div></div>
        </div>
      </div>
    </div>

    <!-- Contact (Read + Edit) -->
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h5 class="section-title mb-3">
          <i class="fa-solid fa-user-pen"></i> Contact Details
          <span class="pill ms-2">Editable</span>
        </h5>

        <!-- Read View -->
        <div id="contactRead">
          <div class="row g-2">
            <div class="col-md-6"><div class="info-item"><div class="text-muted small">Contact Number</div><div><?= h($me_full['contact_number'] ?: '-') ?></div></div></div>
            <div class="col-md-6"><div class="info-item"><div class="text-muted small">Email</div><div><?= h($me_full['email'] ?: '-') ?></div></div></div>
            <div class="col-12"><div class="info-item"><div class="text-muted small">Address</div><div><?= h($me_full['address'] ?: '-') ?></div></div></div>
          </div>
        </div>

        <!-- Edit Form -->
        <form method="post" id="contactEdit" class="mt-2" style="display:none">
          <input type="hidden" name="action" value="update_profile">
          <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label small">Contact Number</label>
              <input class="form-control" name="contact_number" value="<?= h($me_full['contact_number']) ?>" placeholder="03xx-xxxxxxx">
            </div>
            <div class="col-md-6">
              <label class="form-label small">Email</label>
              <input class="form-control" name="email" value="<?= h($me_full['email']) ?>" placeholder="name@example.com">
            </div>
            <div class="col-md-6">
              <label class="form-label small">Father’s Number</label>
              <input class="form-control" name="father_number" value="<?= h($me_full['father_number']) ?>" placeholder="03xx-xxxxxxx">
            </div>
            <div class="col-12">
              <label class="form-label small">Address</label>
              <input class="form-control" name="address" value="<?= h($me_full['address']) ?>" placeholder="House #, Street, City">
            </div>
            <div class="col-12 d-flex gap-2 justify-content-end">
              <button class="btn btn-light border" type="button" id="cancelEdit">Cancel</button>
              <button class="btn btn-primary">Save Changes</button>
            </div>
          </div>
        </form>

      </div>
    </div>

    <!-- Enrollment Snapshot -->
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h5 class="section-title mb-3"><i class="fa-solid fa-book-open"></i> Current / Latest Enrollment</h5>
        <?php if($cur): ?>
          <div class="row g-2">
            <div class="col-md-4"><div class="info-item"><div class="text-muted small">Reg #</div><div><?= h($cur['reg_no']) ?></div></div></div>
            <div class="col-md-4"><div class="info-item"><div class="text-muted small">Course</div><div><?= h($cur['course']) ?></div></div></div>
            <div class="col-md-4"><div class="info-item"><div class="text-muted small">Batch</div><div><?= h($cur['batch'] ?: '-') ?></div></div></div>
            <div class="col-md-4"><div class="info-item"><div class="text-muted small">Start Date</div><div><?= h($cur['start_date'] ?: '-') ?></div></div></div>
            <div class="col-md-4"><div class="info-item"><div class="text-muted small">Registration Status</div><div><?= h($cur['reg_status']) ?></div></div></div>
            <div class="col-md-4">
              <div class="info-item">
                <div class="text-muted small">Fee Status</div>
                <div>
                  <?php
                    $fb = $cur['fee_status']==='PAID' ? '<span class="badge-ok">PAID</span>' :
                          ($cur['fee_status']==='PARTIAL' ? '<span class="badge-warn">PARTIAL</span>' :
                           '<span class="badge-danger">UNPAID</span>');
                    echo $fb;
                  ?>
                </div>
              </div>
            </div>
            <div class="col-md-4"><div class="info-item"><div class="text-muted small">Duration</div><div><?= (int)$cur['duration_months'] ?> months</div></div></div>
            <div class="col-md-8">
              <div class="info-item">
                <div class="text-muted small">Time Slot</div>
                <div>
                  <?php
                    if (!empty($cur['slot_name'])) {
                      echo h($cur['slot_name']).' — '.h($cur['days']).' ('.
                           substr((string)$cur['start_time'],0,5).'–'.substr((string)$cur['end_time'],0,5).')';
                    } else echo '—';
                  ?>
                </div>
              </div>
            </div>
          </div>
        <?php else: ?>
          <div class="text-muted">No current registration.</div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Fee Summary -->
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h5 class="section-title mb-3"><i class="fa-solid fa-money-check-dollar"></i> Fee & Balance</h5>
        <?php if($cur): ?>
          <?php
            $total = $paid = $disc = $extra = $bal = '—';
            $statusBadge = '—';
            if ($fs) {
              $total = number_format((float)($fs['total_fee'] ?? 0));
              $paid  = number_format((float)($fs['paid_amount'] ?? 0));
              $disc  = number_format((float)($fs['discount'] ?? 0));
              $extra = number_format((float)($fs['extra_charges'] ?? 0));
              $balv  = (float)($fs['total_fee'] ?? 0) - (((float)($fs['paid_amount'] ?? 0)) + ((float)($fs['discount'] ?? 0)) - ((float)($fs['extra_charges'] ?? 0)));
              $bal   = number_format($balv);
              $statusBadge =
                ($fs['status'] ?? '')==='PAID'    ? '<span class="badge-ok">PAID</span>' :
                (($fs['status'] ?? '')==='PARTIAL'? '<span class="badge-warn">PARTIAL</span>' :
                                                     '<span class="badge-danger">UNPAID</span>');
            }
          ?>
          <div class="row g-2">
            <div class="col-md-3"><div class="kpi"><div class="label">Fee Model</div><div class="val"><?= ($cur['fee_type']==='PER_MONTH') ? 'Per Month' : 'Per Course' ?></div></div></div>
            <div class="col-md-3"><div class="kpi"><div class="label">Total Fee</div><div class="val"><?= $total ?></div></div></div>
            <div class="col-md-3"><div class="kpi"><div class="label">Paid</div><div class="val"><?= $paid ?></div></div></div>
            <div class="col-md-3"><div class="kpi"><div class="label">Balance</div><div class="val text-danger"><?= $bal ?></div></div></div>
            <div class="col-md-3"><div class="kpi"><div class="label">Discount</div><div class="val"><?= $disc ?></div></div></div>
            <div class="col-md-3"><div class="kpi"><div class="label">Extra</div><div class="val"><?= $extra ?></div></div></div>
            <div class="col-md-3"><div class="kpi"><div class="label">Status</div><div class="val"><?= $statusBadge ?></div></div></div>
            <div class="col-md-3"><div class="kpi"><div class="label">Duration</div><div class="val"><?= (int)($cur['duration_months'] ?? 0) ?> mo</div></div></div>
          </div>
        <?php else: ?>
          <div class="text-muted">Fee info will appear after approval.</div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Registration History -->
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-body">
        <h5 class="section-title mb-3"><i class="fa-regular fa-clock"></i> Registration History</h5>
        <div class="table-responsive">
          <table class="table table-sm align-middle">
            <thead class="table-light">
              <tr>
                <th>Reg #</th>
                <th>Course</th>
                <th>Batch</th>
                <th>Start</th>
                <th>Reg Status</th>
                <th>Fee Status</th>
                <th>Approved At</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $has=false;
              while($r=mysqli_fetch_assoc($regs)):
                $has=true;
                $fsBadge = $r['fee_status']==='PAID' ? '<span class="badge-ok">PAID</span>' :
                          ($r['fee_status']==='PARTIAL' ? '<span class="badge-warn">PARTIAL</span>' :
                           '<span class="badge-danger">UNPAID</span>');
              ?>
                <tr>
                  <td><?= h($r['reg_no']) ?></td>
                  <td><?= h($r['course']) ?></td>
                  <td><?= h($r['batch'] ?: '-') ?></td>
                  <td><?= h($r['start_date'] ?: '-') ?></td>
                  <td><?= h($r['status']) ?></td>
                  <td><?= $fsBadge ?></td>
                  <td><?= h($r['approved_at'] ?: '-') ?></td>
                </tr>
              <?php endwhile; ?>
              <?php if(!$has): ?>
                <tr><td colspan="7" class="text-center text-muted py-4">No registrations yet.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

  </div>
</div>

<!-- Bootstrap JS (isolated – won’t disturb your layout JS) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
// Toggle edit view
const editBtn   = document.getElementById('editToggle');
const readBox   = document.getElementById('contactRead');
const editBox   = document.getElementById('contactEdit');
const cancelBtn = document.getElementById('cancelEdit');

if (editBtn) {
  editBtn.addEventListener('click', () => {
    readBox.style.display = 'none';
    editBox.style.display = '';
    const y = editBox.getBoundingClientRect().top + window.scrollY - 70;
    window.scrollTo({ top: y, behavior: 'smooth' });
  });
}
if (cancelBtn) {
  cancelBtn.addEventListener('click', () => {
    editBox.style.display = 'none';
    readBox.style.display = '';
  });
}
</script>

<?php user_footer(); ?>
