<?php
session_start();
require_once '../config/database.php';

// Only logged-in students
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'student') {
    header('Location: ../login.php');
    exit();
}

// Find student's own student record
$stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE s.user_id = ? LIMIT 1");
$stmt->execute([$_SESSION['user_id']]);
$student = $stmt->fetch();
if (!$student) {
    die('Student profile not found.');
}

$session = $_GET['session'] ?? date('Y');
$exam_type = $_GET['exam_type'] ?? '';

// Load available sessions/exam types for this student
$sessionRows = $pdo->prepare("SELECT DISTINCT session FROM results WHERE student_id = ? ORDER BY session DESC");
$sessionRows->execute([$student['id']]);
$sessions = $sessionRows->fetchAll(PDO::FETCH_COLUMN);

$examRows = $pdo->prepare("SELECT DISTINCT exam_type FROM results WHERE student_id = ? ORDER BY exam_type");
$examRows->execute([$student['id']]);
$exam_types = $examRows->fetchAll(PDO::FETCH_COLUMN);

$results = [];
$total_marks = 0; $total_obtained = 0; $passed_subjects = 0; $total_subjects = 0; $percentage = 0; $overall_grade='';

if ($session && $exam_type) {
    // Get latest unique results per subject for this student
    $stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name, sub.code as subject_code FROM results r LEFT JOIN subjects sub ON r.subject_id = sub.id WHERE r.id IN (SELECT MAX(id) FROM results WHERE student_id=? AND session=? AND exam_type=? GROUP BY subject_id) ORDER BY sub.code, sub.name");
    $stmt->execute([$student['id'], $session, $exam_type]);
    $results = $stmt->fetchAll();

    // Load mark distribution per subject to compute full/pass marks
    foreach ($results as &$row) {
        $stmtD = $pdo->prepare("SELECT total_marks, overall_pass_marks FROM subject_mark_distribution WHERE subject_id=? AND class_id=? AND session=? AND exam_type=? LIMIT 1");
        $stmtD->execute([$row['subject_id'], $student['class_id'], $session, $exam_type]);
        $md = $stmtD->fetch();
        if ($md) {
            $row['full_marks'] = $md['total_marks'];
            $row['pass_marks'] = $md['overall_pass_marks'];
        } else {
            $stmtF = $pdo->prepare("SELECT total_marks, overall_pass_marks FROM mark_distributions WHERE subject_id=? AND class_id=? AND session=? AND exam_type=? LIMIT 1");
            $stmtF->execute([$row['subject_id'], $student['class_id'], $session, $exam_type]);
            $fd = $stmtF->fetch();
            $row['full_marks'] = $fd['total_marks'] ?? 100;
            $row['pass_marks'] = $fd['overall_pass_marks'] ?? 40;
        }
    }
    unset($row);

    $total_subjects = count($results);
    foreach ($results as $r) {
        $total_marks += $r['full_marks'] ?: 100;
        $total_obtained += (float)$r['marks_obtained'];
        if ($r['grade'] !== 'F') $passed_subjects++;
    }
    $percentage = $total_marks>0 ? round(($total_obtained/$total_marks)*100,2) : 0;
    $overall_grade = ($passed_subjects < $total_subjects) ? 'F' : (($percentage>=80)?'A+':(($percentage>=70)?'A':(($percentage>=60)?'A-':(($percentage>=50)?'B':(($percentage>=40)?'C':(($percentage>=33)?'D':'F'))))));
}

// Library info for this student
$library_issues = [];
try {
    $stmt = $pdo->prepare("SELECT li.*, lb.title, lb.author FROM library_issues li JOIN library_books lb ON lb.id = li.book_id WHERE li.student_id = ? ORDER BY (li.status='issued') DESC, li.issue_date DESC");
    $stmt->execute([$student['id']]);
    $library_issues = $stmt->fetchAll();
} catch (Exception $e) {
    $library_issues = [];
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>আমার ফলাফল</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">
  <link href="../assets/css/style.css" rel="stylesheet">
  <style>
    @media print {
      .no-print { display: none !important; }
      body { font-size: 12px; }
      .container-fluid { max-width: 100% !important; }
      .marksheet { page-break-inside: avoid; }
    }
    .marksheet { border: 2px solid #000; padding: 20px; margin: 20px 0; background: #fff; }
    .school-header { text-align: center; border-bottom: 2px solid #000; padding-bottom: 10px; margin-bottom: 15px; }
    .school-logo { width: 70px; height: 70px; border:2px solid #000; border-radius: 50%; display:inline-flex; align-items:center; justify-content:center; font-size:22px; background:#f8f9fa; }
    .student-info { display:grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 10px; }
    .info-row { display:flex; margin-bottom:6px; }
    .info-label { font-weight:bold; min-width:110px; }
    .info-value { border-bottom:1px solid #000; flex:1; padding-left:8px; }
    .marks-table { width:100%; border-collapse: collapse; }
    .marks-table th, .marks-table td { border:1px solid #000; padding:6px; text-align:center; }
    .marks-table th { background:#f8f9fa; }
    .signature-section { display:grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-top: 30px; text-align:center; }
    .signature-box { border-top:1px solid #000; padding-top:8px; margin-top:40px; }
  </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
  <div class="container-fluid">
    <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম</a>
    <div class="navbar-nav ms-auto">
      <button class="btn btn-light" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট মার্কশীট</button>
      <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
    </div>
  </div>
</nav>
<div class="container-fluid mt-4">
  <div class="card no-print">
    <div class="card-header"><h5><i class="fas fa-file-alt"></i> আমার ফলাফল</h5></div>
    <div class="card-body">
      <div class="row mb-3">
        <div class="col-md-4"><strong>নাম:</strong> <?=htmlspecialchars($student['first_name'].' '.$student['last_name'])?></div>
        <div class="col-md-4"><strong>আইডি:</strong> <?=htmlspecialchars($student['student_id'])?></div>
        <div class="col-md-4"><strong>ক্লাস:</strong> <?=htmlspecialchars(($student['class_name']??'').' - '.($student['section']??''))?></div>
      </div>

      <form method="GET" class="row g-3 mb-3">
        <div class="col-md-3">
          <label class="form-label">সেশন</label>
          <select name="session" class="form-select">
            <option value="">নির্বাচন করুন</option>
            <?php foreach ($sessions as $s): ?>
              <option value="<?=htmlspecialchars($s)?>" <?=$session==$s?'selected':''?>><?=htmlspecialchars($s)?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">পরীক্ষা</label>
          <select name="exam_type" class="form-select">
            <option value="">নির্বাচন করুন</option>
            <?php foreach ($exam_types as $et): ?>
              <option value="<?=htmlspecialchars($et)?>" <?=$exam_type==$et?'selected':''?>><?=htmlspecialchars($et)?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3 align-self-end">
          <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i> দেখুন</button>
        </div>
      </form>
    </div>
  </div>

  <?php if ($session && $exam_type && !empty($results)): ?>
  <!-- Printable Marksheet -->
  <div class="marksheet">
    <div class="school-header">
      <div class="school-logo"><i class="fas fa-school"></i></div>
      <h4 class="mt-2 mb-0">বিদ্যা নিকেতন</h4>
      <small>পরীক্ষার ফলাফল - <?=htmlspecialchars($session)?> (<?=htmlspecialchars($exam_type)?>)</small>
    </div>

    <div class="student-info">
      <div>
        <div class="info-row"><div class="info-label">নাম</div><div class="info-value"><?=htmlspecialchars($student['first_name'].' '.$student['last_name'])?></div></div>
        <div class="info-row"><div class="info-label">শিক্ষার্থী আইডি</div><div class="info-value"><?=htmlspecialchars($student['student_id'])?></div></div>
      </div>
      <div>
        <div class="info-row"><div class="info-label">ক্লাস</div><div class="info-value"><?=htmlspecialchars(($student['class_name']??'').' - '.($student['section']??''))?></div></div>
        <div class="info-row"><div class="info-label">গ্রুপ</div><div class="info-value"><?=htmlspecialchars($student['group_name'] ?? '-')?></div></div>
      </div>
    </div>

    <div class="table-responsive">
      <table class="marks-table">
        <thead><tr><th>বিষয়</th><th>পূর্ণ নম্বর</th><th>পাস নম্বর</th><th>প্রাপ্ত নম্বর</th><th>গ্রেড</th></tr></thead>
        <tbody>
          <?php foreach ($results as $r): ?>
          <tr>
            <td><?=htmlspecialchars($r['subject_name'])?></td>
            <td><?= (int)($r['full_marks'] ?: 100) ?></td>
            <td><?= (int)($r['pass_marks'] ?: 40) ?></td>
            <td><?= htmlspecialchars($r['marks_obtained']) ?></td>
            <td><?= htmlspecialchars($r['grade']) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <div class="row mt-3">
      <div class="col-md-3"><strong>মোট নম্বর:</strong> <?=$total_marks?></div>
      <div class="col-md-3"><strong>প্রাপ্ত:</strong> <?=$total_obtained?></div>
      <div class="col-md-3"><strong>পাস বিষয়:</strong> <?=$passed_subjects?> / <?=$total_subjects?></div>
      <div class="col-md-3"><strong>শতকরা:</strong> <?=$percentage?>% (গ্রেড: <?=$overall_grade?>)</div>
    </div>

    <div class="signature-section">
      <div class="signature-box">শ্রেণি শিক্ষক</div>
      <div class="signature-box">পরীক্ষা নিয়ন্ত্রক</div>
      <div class="signature-box">প্রধান শিক্ষক</div>
    </div>
  </div>
  <?php elseif ($session && $exam_type): ?>
    <div class="alert alert-info">এই সেশনে/পরীক্ষায় কোন ফলাফল পাওয়া যায়নি।</div>
  <?php else: ?>
    <div class="alert alert-warning no-print">উপরে থেকে সেশন ও পরীক্ষা নির্বাচন করুন এবং তারপর প্রিন্ট করুন।</div>
  <?php endif; ?>

  <!-- Library Info (not printed in marksheet) -->
  <div class="card mt-4 no-print">
    <div class="card-header"><h6><i class="fas fa-book-open"></i> লাইব্রেরি তথ্য</h6></div>
    <div class="card-body">
      <?php if (empty($library_issues)): ?>
        <div class="text-muted">কোন লাইব্রেরি রেকর্ড পাওয়া যায়নি।</div>
      <?php else: ?>
        <div class="table-responsive">
          <table class="table table-sm table-striped">
            <thead><tr><th>বই</th><th>ইস্যু তারিখ</th><th>ডিউ তারিখ</th><th>রিটার্ন তারিখ</th><th>অবস্থা</th></tr></thead>
            <tbody>
              <?php foreach ($library_issues as $li): 
                $overdue = ($li['status']==='issued' && !empty($li['due_date']) && strtotime($li['due_date']) < time());
              ?>
              <tr class="<?= $overdue ? 'table-warning' : '' ?>">
                <td><?=htmlspecialchars($li['title'])?><?php if(!empty($li['author'])) echo ' - <small class="text-muted">'.htmlspecialchars($li['author']).'</small>'; ?></td>
                <td><?=htmlspecialchars($li['issue_date'] ?? '-')?></td>
                <td><?=htmlspecialchars($li['due_date'] ?? '-')?></td>
                <td><?=htmlspecialchars($li['return_date'] ?? '-')?></td>
                <td>
                  <?php if ($li['status']==='issued'): ?>
                    <span class="badge bg-primary">জারিকৃত</span>
                    <?php if ($overdue): ?><span class="badge bg-danger">ওভারডিউ</span><?php endif; ?>
                  <?php elseif ($li['status']==='returned'): ?>
                    <span class="badge bg-success">রিটার্নড</span>
                  <?php elseif ($li['status']==='overdue'): ?>
                    <span class="badge bg-danger">ওভারডিউ</span>
                  <?php elseif ($li['status']==='lost'): ?>
                    <span class="badge bg-dark">হারানো</span>
                  <?php else: ?>
                    <span class="badge bg-secondary"><?=htmlspecialchars($li['status'])?></span>
                  <?php endif; ?>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
      <small class="text-muted"><i class="fas fa-info-circle"></i> লাইব্রেরি সেকশনের তথ্য প্রিন্টে অন্তর্ভুক্ত হবে না।</small>
    </div>
  </div>

</div>
</body>
</html>