<?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');}
}

/* --------------------------------------------------
   Load Student + Registration + Course + Batch Info
-------------------------------------------------- */
$me = mysqli_fetch_assoc(mysqli_query($conn,"
  SELECT id, full_name, father_name, gender, cnic, dob,
         contact_number, email, address, created_at
  FROM students WHERE id={$student_id} LIMIT 1
"));

$reg = mysqli_fetch_assoc(mysqli_query($conn,"
  SELECT r.reg_no,r.course_id,r.batch_id,r.fee_status,r.status AS reg_status,
         c.name AS course,c.fee_type,c.course_fee,c.monthly_fee,c.duration_months,
         b.name AS batch,b.start_date,b.end_date,b.status AS batch_status,
         ts.name AS slot_name,ts.start_time,ts.end_time,ts.days
  FROM registrations r
  JOIN courses c ON c.id=r.course_id
  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
"));

$course_id = $reg['course_id'] ?? 0;
$batch_id  = $reg['batch_id']  ?? 0;

/* --------------------------------------------------
   Fee Summary
-------------------------------------------------- */
$fee = mysqli_fetch_assoc(mysqli_query($conn,"
  SELECT total_fee,paid_amount,discount,extra_charges,status,updated_at
  FROM fee_payments WHERE student_id={$student_id} AND course_id={$course_id}
  ORDER BY updated_at DESC LIMIT 1
"));
$total_fee = $fee['total_fee'] ?? 0;
$paid      = $fee['paid_amount'] ?? 0;
$discount  = $fee['discount'] ?? 0;
$extra     = $fee['extra_charges'] ?? 0;
$balance   = max(0, $total_fee + $extra - $discount - $paid);
$fee_status= $fee['status'] ?? 'UNPAID';

/* --------------------------------------------------
   Attendance Summary (current month)
-------------------------------------------------- */
$month = date('Y-m');
$att = mysqli_fetch_assoc(mysqli_query($conn,"
  SELECT presents,absents,leaves,total_days
  FROM attendance_summary
  WHERE student_id={$student_id} AND month_year='$month'
"));
$pres=$att['presents']??0; $abs=$att['absents']??0; $lea=$att['leaves']??0; $tot=$att['total_days']??0;
$attPct = $tot ? round(($pres/$tot)*100,1) : 0;

/* --------------------------------------------------
   Latest Classes + Daily Work
-------------------------------------------------- */
$classes = mysqli_query($conn,"
  SELECT id,title,visible_from
  FROM daily_classes
  WHERE is_active=1 AND course_id={$course_id}
        AND (batch_id IS NULL OR batch_id={$batch_id})
        AND visible_from<=NOW()
  ORDER BY visible_from DESC LIMIT 5
");

$works = mysqli_query($conn,"
  SELECT id,title,work_date,points_obtained,points_max,status
  FROM daily_work_submissions
  WHERE student_id={$student_id}
  ORDER BY created_at DESC LIMIT 5
");

/* --------------------------------------------------
   KPI counts
-------------------------------------------------- */
$workMonth = (int)mysqli_fetch_assoc(mysqli_query($conn,"
  SELECT COUNT(*) c FROM daily_work_submissions
  WHERE student_id={$student_id} AND DATE_FORMAT(created_at,'%Y-%m')='$month'
"))['c'];

$class30 = (int)mysqli_fetch_assoc(mysqli_query($conn,"
  SELECT COUNT(*) c FROM daily_classes
  WHERE is_active=1 AND course_id={$course_id}
    AND (batch_id IS NULL OR batch_id={$batch_id})
    AND visible_from >= DATE_SUB(NOW(),INTERVAL 30 DAY)
"))['c'];

user_header('Student Dashboard');
?>
<style>
  body{background:#f8fafc}
  .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:12px}
  .card{background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:16px;box-shadow:0 2px 6px rgba(0,0,0,.05)}
  h2,h3{margin:0 0 6px;color:#1e3a8a}
  .muted{color:#64748b;font-size:13px}
  .kpi{display:flex;align-items:center;justify-content:space-between;padding:10px;border:1px solid #e5e7eb;border-radius:10px;margin-bottom:6px}
  .val{font-weight:700;font-size:22px}
  .badge{padding:3px 8px;border-radius:999px;font-size:12px;font-weight:600}
  .PAID{background:#dcfce7;color:#166534;border:1px solid #86efac}
  .PARTIAL{background:#fff7ed;color:#9a3412;border:1px solid #fed7aa}
  .UNPAID{background:#fee2e2;color:#991b1b;border:1px solid #fecaca}
  .progress{height:8px;background:#e5e7eb;border-radius:999px;overflow:hidden;margin-top:6px}
  .bar{height:8px;background:#2563eb;width:<?=$attPct?>%}
  table{width:100%;border-collapse:collapse;margin-top:6px}
  th,td{padding:8px 10px;border-bottom:1px solid #e5e7eb;text-align:left}
  thead{background:#f1f5f9}
  a.btn{display:inline-block;padding:6px 12px;border-radius:8px;border:1px solid #e5e7eb;text-decoration:none;color:#0f172a}
  a.btn.primary{background:#2563eb;color:#fff;border-color:#2563eb}
  @media(max-width:700px){.grid{grid-template-columns:1fr}}
</style>

<h2>Welcome, <?=h($me['full_name'])?></h2>
<div class="muted">Last login: <?=h(date('d M Y',strtotime($me['created_at'])))?> • Reg No: <?=h($reg['reg_no']??'N/A')?></div>

<!-- KPIs -->
<div class="grid" style="margin-top:14px">
  <div class="card">
    <h3>Fees Overview</h3>
    <div class="kpi"><span>Total Fee</span><span class="val">PKR <?=number_format($total_fee)?></span></div>
    <div class="kpi"><span>Paid</span><span class="val">PKR <?=number_format($paid)?></span></div>
    <div class="kpi"><span>Balance</span><span class="val">PKR <?=number_format($balance)?></span></div>
    <div class="kpi"><span>Status</span><span class="badge <?=$fee_status?>"><?=$fee_status?></span></div>
    <a href="fees_overview.php" class="btn primary" style="margin-top:8px">View Fee Details</a>
  </div>

  <div class="card">
    <h3>Attendance</h3>
    <div class="kpi"><span>Month</span><span><?=date('F Y')?></span></div>
    <div class="kpi"><span>Present</span><span><?=$pres?></span></div>
    <div class="kpi"><span>Absent</span><span><?=$abs?></span></div>
    <div class="kpi"><span>Leave</span><span><?=$lea?></span></div>
    <div class="progress"><div class="bar"></div></div>
    <div class="muted" style="margin-top:4px">Attendance <?=$attPct?> %</div>
  </div>

  <div class="card">
    <h3>Course & Batch</h3>
    <div class="kpi"><span>Course</span><span><?=h($reg['course']??'–')?></span></div>
    <div class="kpi"><span>Batch</span><span><?=h($reg['batch']??'–')?></span></div>
    <div class="kpi"><span>Timing</span>
      <span><?=h($reg['slot_name']??'')?> <?=h(substr($reg['start_time']??'',0,5))?>‑<?=h(substr($reg['end_time']??'',0,5))?></span>
    </div>
    <div class="kpi"><span>Days</span><span><?=h($reg['days']??'')?></span></div>
  </div>
</div>

<!-- Classes & Work -->
<div class="grid" style="margin-top:14px">
  <div class="card">
    <h3>Latest Classes</h3>
    <table>
      <thead><tr><th>Title</th><th>Date</th></tr></thead>
      <tbody>
      <?php if(mysqli_num_rows($classes)>0): while($c=mysqli_fetch_assoc($classes)): ?>
        <tr><td><?=h($c['title'])?></td><td><?=date('d M H:i',strtotime($c['visible_from']))?></td></tr>
      <?php endwhile; else: ?><tr><td colspan="2" class="muted">No classes yet</td></tr><?php endif; ?>
      </tbody>
    </table>
    <a href="daily_classes.php" class="btn primary" style="margin-top:8px">View All Classes</a>
  </div>

  <div class="card">
    <h3>Daily Work</h3>
    <table>
      <thead><tr><th>Title</th><th>Status</th><th>Points</th></tr></thead>
      <tbody>
      <?php if(mysqli_num_rows($works)>0): while($w=mysqli_fetch_assoc($works)): ?>
        <tr>
          <td><?=h($w['title'])?></td>
          <td><span class="badge <?=h($w['status'])?>"><?=h($w['status'])?></span></td>
          <td><?=is_null($w['points_obtained'])?'–':$w['points_obtained'].'/'.$w['points_max']?></td>
        </tr>
      <?php endwhile; else: ?><tr><td colspan="3" class="muted">No submissions</td></tr><?php endif; ?>
      </tbody>
    </table>
    <a href="daily_work.php" class="btn primary" style="margin-top:8px">Go to Daily Work</a>
  </div>
</div>

<!-- Quick Stats -->
<div class="grid" style="margin-top:14px">
  <div class="card">
    <h3>Quick Stats</h3>
    <div class="kpi"><span>Classes (last 30 days)</span><span class="val"><?=$class30?></span></div>
    <div class="kpi"><span>Work this month</span><span class="val"><?=$workMonth?></span></div>
    <div class="kpi"><span>Fee Status</span><span class="badge <?=$fee_status?>"><?=$fee_status?></span></div>
    <div class="kpi"><span>Attendance %</span><span class="val"><?=$attPct?> %</span></div>
  </div>

  <div class="card">
    <h3>Quick Links</h3>
    <a href="profile.php" class="btn" style="margin:4px">👤 My Profile</a>
    <a href="daily_classes.php" class="btn" style="margin:4px">📘 Classes</a>
    <a href="daily_work.php" class="btn" style="margin:4px">📝 Daily Work</a>
    <a href="fees_overview.php" class="btn" style="margin:4px">💰 Fees</a>
    <a href="support.php" class="btn" style="margin:4px">🎧 Support</a>
  </div>
</div>

<?php user_footer(); ?>
