<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
requireLogin();
$uid = $_SESSION['user_id'];

// ── Ensure weekly_target_hours column exists (safe migration) ──────────
try {
    $pdo->exec("ALTER TABLE subjects ADD COLUMN weekly_target_hours DECIMAL(4,1) DEFAULT 0");
} catch (PDOException $e) { /* already exists — ignore */ }

// ── AJAX handler ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $limitCheck = checkSubjectLimit($uid);
        if (!$limitCheck['allowed']) {
            jsonResponse([
                'success'      => false,
                'limit_reached'=> true,
                'message'      => "You've reached the free plan limit of {$limitCheck['limit']} subjects. Upgrade to Pro for unlimited subjects.",
            ]);
        }

        $name         = sanitize($_POST['name'] ?? '');
        $color        = preg_match('/^#[0-9a-fA-F]{6}$/', $_POST['color'] ?? '') ? $_POST['color'] : '#6366f1';
        $target_marks = min(100, max(1, (float)($_POST['target_marks'] ?? 75)));
        $weekly_hrs   = max(0, min(168, (float)($_POST['weekly_target_hours'] ?? 0)));

        if ($name === '')
            jsonResponse(['success'=>false, 'message'=>'Subject name is required.']);

        $dup = $pdo->prepare("SELECT id FROM subjects WHERE user_id=? AND name=?");
        $dup->execute([$uid, $name]);
        if ($dup->fetch())
            jsonResponse(['success'=>false, 'message'=>'You already have a subject with that name.']);

        $pdo->prepare("INSERT INTO subjects (user_id,name,color,target_marks,weekly_target_hours) VALUES (?,?,?,?,?)")
            ->execute([$uid, $name, $color, $target_marks, $weekly_hrs]);

        jsonResponse(['success'=>true, 'message'=>'Subject "' . htmlspecialchars($name) . '" added!']);
    }

    if ($action === 'set_weekly_target') {
        $id  = (int)($_POST['id'] ?? 0);
        $hrs = max(0, min(168, (float)($_POST['weekly_target_hours'] ?? 0)));
        $pdo->prepare("UPDATE subjects SET weekly_target_hours=? WHERE id=? AND user_id=?")
            ->execute([$hrs, $id, $uid]);
        jsonResponse(['success'=>true, 'message'=>'Weekly target updated!']);
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("DELETE FROM subjects WHERE id=? AND user_id=?")->execute([$id, $uid]);
        jsonResponse(['success'=>true, 'message'=>'Subject deleted.']);
    }

    jsonResponse(['success'=>false, 'message'=>'Unknown action.']);
}

// ── Page data ────────────────────────────────────────────────────────
$weekStart = date('Y-m-d', strtotime('monday this week'));

$subjectsQ = $pdo->prepare("
    SELECT s.*,
           COUNT(DISTINCT ss.id)                                   AS session_count,
           COALESCE(SUM(ss.duration_minutes),0)                    AS total_mins,
           COUNT(DISTINCT m.id)                                     AS exam_count,
           COALESCE(AVG((m.marks_obtained/m.total_marks)*100),0)   AS avg_score,
           COALESCE(SUM(CASE WHEN ss.date >= ? THEN ss.duration_minutes ELSE 0 END),0) AS week_mins
    FROM   subjects s
    LEFT JOIN study_sessions ss ON s.id = ss.subject_id
    LEFT JOIN marks           m  ON s.id = m.subject_id
    WHERE  s.user_id = ?
    GROUP  BY s.id
    ORDER  BY s.name
");
$subjectsQ->execute([$weekStart, $uid]);
$subjects = $subjectsQ->fetchAll();

$subLimit = checkSubjectLimit($uid);

require_once 'includes/header.php';
renderHeader('Subjects', 'subjects');
?>

<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:22px">
  <div>
    <div style="font-size:22px;font-weight:800">📚 Subjects</div>
    <div style="font-size:13px;color:var(--text-muted);margin-top:3px"><?= count($subjects) ?> subjects · Week of <?= date('M j', strtotime($weekStart)) ?></div>
  </div>
  <button class="btn btn-primary" id="addSubjectBtn" onclick="<?= $subLimit['allowed'] ? "openModal('addSubjectModal')" : "location.href='upgrade.php'" ?>">
    <?= $subLimit['allowed'] ? '+ Add Subject' : '⚡ Upgrade for More' ?>
  </button>
</div>

<?php if (!$subLimit['is_pro']): ?>
<div class="card" style="margin-bottom:18px;padding:14px 16px;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;<?= !$subLimit['allowed'] ? 'border-color:rgba(239,68,68,.35)' : '' ?>">
  <div style="font-size:13px;color:var(--text-secondary)">
    <?php if ($subLimit['allowed']): ?>
      📚 Free plan: <strong style="color:var(--text-primary)"><?= $subLimit['used'] ?>/<?= $subLimit['limit'] ?></strong> subjects used
    <?php else: ?>
      ⚠️ You've reached the free plan limit of <strong style="color:var(--text-primary)"><?= $subLimit['limit'] ?> subjects</strong>.
    <?php endif; ?>
  </div>
  
</div>
<?php endif; ?>

<?php if ($subjects): ?>
<div class="grid-3">
<?php foreach ($subjects as $sub):
  $avg              = round($sub['avg_score'], 1);
  $markTarget       = (float)$sub['target_marks'];
  $markPct          = $markTarget > 0 ? min(round(($avg / $markTarget) * 100), 100) : 0;
  $markCls          = $avg >= $markTarget ? 'green' : ($avg >= 50 ? 'yellow' : 'red');
  $weeklyTargetMins = (float)$sub['weekly_target_hours'] * 60;
  $weekMins         = (int)$sub['week_mins'];
  $weekPct          = $weeklyTargetMins > 0 ? min(100, round(($weekMins / $weeklyTargetMins) * 100)) : 0;
  $weekH            = floor($weekMins / 60);
  $weekM            = $weekMins % 60;
  $targetH          = floor($weeklyTargetMins / 60);
  $targetM          = (int)$weeklyTargetMins % 60;
  $weekDone         = $weeklyTargetMins > 0 && $weekMins >= $weeklyTargetMins;
?>
<div class="card" style="border-top:3px solid <?= htmlspecialchars($sub['color']) ?>">
  <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:14px;gap:8px;min-width:0">
    <div style="min-width:0;flex:1;overflow:hidden">
      <h3 style="font-size:16px;font-weight:700;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= htmlspecialchars($sub['name']) ?></h3>
      <span style="font-size:12px;color:var(--text-muted)">Target score: <?= $markTarget ?>%</span>
    </div>
    <div style="display:flex;gap:6px;flex-shrink:0">
      <button class="btn btn-secondary btn-sm btn-icon" title="Set weekly target"
        onclick="openWeeklyTarget(<?= $sub['id'] ?>, '<?= htmlspecialchars(addslashes($sub['name'])) ?>', <?= (float)$sub['weekly_target_hours'] ?>)">🎯</button>
      <button class="btn btn-danger btn-sm btn-icon"
        onclick="deleteSub(<?= $sub['id'] ?>, '<?= htmlspecialchars(addslashes($sub['name'])) ?>')">🗑️</button>
    </div>
  </div>

  <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px">
    <div style="background:var(--bg-secondary);border-radius:10px;padding:11px;text-align:center">
      <div style="font-size:17px;font-weight:700;color:var(--text-primary)"><?= $sub['session_count'] ?></div>
      <div style="font-size:11px;color:var(--text-muted)">Sessions</div>
    </div>
    <div style="background:var(--bg-secondary);border-radius:10px;padding:11px;text-align:center">
      <div style="font-size:17px;font-weight:700;color:var(--text-primary)"><?= floor($sub['total_mins']/60) ?>h <?= $sub['total_mins']%60 ?>m</div>
      <div style="font-size:11px;color:var(--text-muted)">Total Studied</div>
    </div>
  </div>

  <!-- Weekly target progress -->
  <?php if ($sub['weekly_target_hours'] > 0): ?>
  <div style="background:var(--bg-secondary);border-radius:12px;padding:12px;margin-bottom:12px">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
      <span style="font-size:12px;font-weight:600;color:var(--text-secondary)">
        📅 This Week
        <?php if ($weekDone): ?>
        <span style="background:rgba(16,185,129,0.15);color:var(--success);font-size:10px;padding:2px 7px;border-radius:20px;margin-left:5px;font-weight:700">✓ DONE</span>
        <?php endif; ?>
      </span>
      <span style="font-size:12px;font-weight:700;color:<?= $weekDone ? 'var(--success)' : 'var(--text-primary)' ?>">
        <?= $weekH ?>h <?= $weekM ?>m / <?= $targetH ?>h<?= $targetM > 0 ? ' '.$targetM.'m' : '' ?>
      </span>
    </div>
    <div class="progress-bar" style="height:8px">
      <div class="progress-fill <?= $weekPct >= 100 ? 'green' : ($weekPct >= 60 ? 'yellow' : '') ?>"
           style="width:<?= $weekPct ?>%;<?= $weekPct < 60 ? 'background:'.htmlspecialchars($sub['color']) : '' ?>"></div>
    </div>
    <div style="font-size:11px;color:var(--text-muted);margin-top:5px"><?= $weekPct ?>% of weekly goal</div>
  </div>
  <?php else: ?>
  <div style="border:1px dashed var(--border);border-radius:10px;padding:10px;text-align:center;margin-bottom:12px;cursor:pointer"
       onclick="openWeeklyTarget(<?= $sub['id'] ?>, '<?= htmlspecialchars(addslashes($sub['name'])) ?>', 0)">
    <span style="font-size:12px;color:var(--text-muted)">🎯 Set weekly study target</span>
  </div>
  <?php endif; ?>

  <?php if ($sub['exam_count'] > 0): ?>
  <div>
    <div style="display:flex;justify-content:space-between;margin-bottom:5px">
      <span style="font-size:12px;color:var(--text-muted)">Avg Score</span>
      <span style="font-size:12px;font-weight:600;color:var(--text-primary)"><?= $avg ?>%</span>
    </div>
    <div class="progress-bar">
      <div class="progress-fill <?= $markCls ?>" style="width:<?= $markPct ?>%;background:<?= htmlspecialchars($sub['color']) ?>"></div>
    </div>
  </div>
  <?php else: ?>
  <div style="font-size:12px;color:var(--text-muted);text-align:center;padding:4px 0">No exams recorded yet</div>
  <?php endif; ?>
</div>
<?php endforeach; ?>
</div>

<?php else: ?>
<div class="card">
  <div class="empty-state">
    <div class="empty-icon">📖</div>
    <h3>No subjects yet</h3>
    <p>Click "Add Subject" to get started</p>
  </div>
</div>
<?php endif; ?>

<!-- ── Add Subject Modal ──────────────────────────────────────────── -->
<div class="modal-overlay" id="addSubjectModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title">➕ Add Subject</div>
      <button class="modal-close" onclick="closeModal('addSubjectModal')">✕</button>
    </div>
    <div id="subjectMsgBox" style="display:none" class="alert"></div>
    <div class="form-group">
      <label class="form-label">Subject Name *</label>
      <input type="text" id="sub_name" class="form-control" placeholder="e.g. Combined Maths, Physics">
    </div>
    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">Colour</label>
        <input type="color" id="sub_color" class="form-control" value="#6366f1" style="height:48px;padding:4px 8px;cursor:pointer">
      </div>
      <div class="form-group">
        <label class="form-label">Target Score (%)</label>
        <input type="number" id="sub_target" class="form-control" value="75" min="1" max="100">
      </div>
    </div>
    <div class="form-group">
      <label class="form-label">Weekly Study Target (hours) <span style="color:var(--text-muted);font-weight:400">— optional</span></label>
      <input type="number" id="sub_weekly" class="form-control" value="0" min="0" max="168" step="0.5" placeholder="e.g. 5">
      <div style="font-size:12px;color:var(--text-muted);margin-top:5px">Set 0 to skip. You can change this any time via the 🎯 button.</div>
    </div>
    <button id="subSaveBtn" class="btn btn-primary btn-full" onclick="saveSubject()">Add Subject</button>
  </div>
</div>

<!-- ── Weekly Target Modal ───────────────────────────────────────── -->
<div class="modal-overlay" id="weeklyTargetModal">
  <div class="modal" style="max-width:380px">
    <div class="modal-header">
      <div class="modal-title">🎯 Weekly Study Target</div>
      <button class="modal-close" onclick="closeModal('weeklyTargetModal')">✕</button>
    </div>
    <input type="hidden" id="wt_subject_id">
    <div style="margin-bottom:16px">
      <div style="font-size:15px;font-weight:700;color:var(--text-primary);margin-bottom:4px" id="wt_subject_name"></div>
      <div style="font-size:13px;color:var(--text-muted)">How many hours do you want to study this subject per week?</div>
    </div>
    <div id="wtMsgBox" style="display:none" class="alert"></div>
    <div class="form-group">
      <label class="form-label">Weekly Hours Target</label>
      <input type="number" id="wt_hours" class="form-control" min="0" max="168" step="0.5" placeholder="e.g. 5">
    </div>
    <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:18px">
      <div style="font-size:12px;color:var(--text-muted);width:100%;margin-bottom:2px">Quick set:</div>
      <?php foreach ([1,2,3,5,7,10] as $h): ?>
      <button class="btn btn-secondary btn-sm" onclick="document.getElementById('wt_hours').value=<?= $h ?>"><?= $h ?>h</button>
      <?php endforeach; ?>
      <button class="btn btn-sm" style="background:rgba(239,68,68,0.1);color:var(--danger);border:1px solid rgba(239,68,68,0.2)"
              onclick="document.getElementById('wt_hours').value=0">Remove target</button>
    </div>
    <button id="wtSaveBtn" class="btn btn-primary btn-full" onclick="saveWeeklyTarget()">Save Target</button>
  </div>
</div>

<script>
function showSubMsg(msg, type) {
  var el = document.getElementById('subjectMsgBox');
  el.className = 'alert alert-' + type;
  el.innerHTML = (type==='error' ? '⚠️ ' : '✅ ') + msg;
  el.style.display = 'flex';
}

async function saveSubject() {
  var name   = document.getElementById('sub_name').value.trim();
  var color  = document.getElementById('sub_color').value;
  var target = document.getElementById('sub_target').value;
  var weekly = parseFloat(document.getElementById('sub_weekly').value) || 0;
  if (!name) { showSubMsg('Please enter a subject name.', 'error'); return; }
  var btn = document.getElementById('subSaveBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span>&nbsp; Saving...';
  try {
    var fd = new FormData();
    fd.append('action','add'); fd.append('name',name); fd.append('color',color);
    fd.append('target_marks',target); fd.append('weekly_target_hours',weekly);
    var res = await fetch(window.location.href,{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    var data = await res.json();
    if (data.success) { showSubMsg(data.message,'success'); document.getElementById('sub_name').value=''; setTimeout(function(){ closeModal('addSubjectModal'); location.reload(); },900); }
    else { showSubMsg(data.message,'error'); btn.disabled=false; btn.innerHTML='Add Subject'; }
  } catch(e) { showSubMsg('Connection error.','error'); btn.disabled=false; btn.innerHTML='Add Subject'; }
}
document.getElementById('sub_name').addEventListener('keydown',function(e){ if(e.key==='Enter') saveSubject(); });

async function deleteSub(id, name) {
  if (!(await stConfirm('Delete "'+name+'"? All study sessions and marks will also be deleted.'))) return;
  try {
    var fd = new FormData(); fd.append('action','delete'); fd.append('id',id);
    var res = await fetch(window.location.href,{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    var data = await res.json();
    if (data.success) location.reload(); else alert(data.message);
  } catch(e) { alert('Connection error.'); }
}

function openWeeklyTarget(id, name, currentHrs) {
  document.getElementById('wt_subject_id').value = id;
  document.getElementById('wt_subject_name').textContent = name;
  document.getElementById('wt_hours').value = currentHrs > 0 ? currentHrs : '';
  document.getElementById('wtMsgBox').style.display = 'none';
  openModal('weeklyTargetModal');
}

async function saveWeeklyTarget() {
  var id  = document.getElementById('wt_subject_id').value;
  var hrs = parseFloat(document.getElementById('wt_hours').value) || 0;
  var btn = document.getElementById('wtSaveBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span>&nbsp; Saving...';
  try {
    var fd = new FormData();
    fd.append('action','set_weekly_target'); fd.append('id',id); fd.append('weekly_target_hours',hrs);
    var res = await fetch(window.location.href,{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    var data = await res.json();
    if (data.success) {
      var msg = document.getElementById('wtMsgBox');
      msg.className='alert alert-success'; msg.textContent = hrs>0 ? '✅ Target set: '+hrs+'h/week' : '✅ Target removed.'; msg.style.display='flex';
      setTimeout(function(){ closeModal('weeklyTargetModal'); location.reload(); },900);
    } else { alert(data.message); btn.disabled=false; btn.innerHTML='Save Target'; }
  } catch(e) { alert('Connection error.'); btn.disabled=false; btn.innerHTML='Save Target'; }
}
</script>

<?php require_once 'includes/footer.php'; renderFooter(); ?>
