<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db = Database::getInstance();
$page = 'Training Management';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = post('action');
    // FIX (07 Jul 2026): training_programs had no org concept at all —
    // added company_id (migration_training_programs_company.sql) and
    // scoped everything below to the current org.
    $orgCompanies = orgCompanyIds($db);
    $companyId    = $orgCompanies[0] ?? 0;
    if ($action === 'save_program') {
        $id = postInt('id');
        if ($id) {
            $owned = $db->fetchOne("SELECT id FROM training_programs WHERE id=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")", array_merge([$id], $orgCompanies));
            if (!$owned) { setFlash('error','Program not found.'); header('Location: ' . BASE_URL . '/modules/training/index.php'); exit; }
            $db->execute("UPDATE training_programs SET title=?,description=?,from_date=?,to_date=?,duration_hours=?,mode=?,location=?,max_participants=?,status=? WHERE id=?",
                [post('title'), post('description'), post('from_date'), post('to_date'),
                 postInt('hours'), post('mode'), post('location'), postInt('max_p'), post('status'), $id]);
        } else {
            $db->execute("INSERT INTO training_programs (company_id,title,description,from_date,to_date,duration_hours,mode,location,max_participants,status) VALUES (?,?,?,?,?,?,?,?,?,'planned')",
                [$companyId, post('title'), post('description'), post('from_date'), post('to_date'),
                 postInt('hours'), post('mode'), post('location'), postInt('max_p')]);
        }
        setFlash('success', 'Training program saved.');
    } elseif ($action === 'enroll') {
        $progId = postInt('prog_id'); $empId = postInt('emp_id');
        $progOwned = $db->fetchOne("SELECT id FROM training_programs WHERE id=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")", array_merge([$progId], $orgCompanies));
        $empOwned  = $db->fetchOne("SELECT company_id FROM employees WHERE id=?", [$empId]);
        if (!$progOwned || !$empOwned || !in_array($empOwned['company_id'], $orgCompanies)) {
            setFlash('error', 'Program or employee not found.');
        } else {
            $db->execute("INSERT IGNORE INTO training_enrollment (training_id,employee_id,enrolled_date,attendance_status) VALUES (?,?,CURDATE(),'enrolled')",
                [$progId, $empId]);
            setFlash('success', 'Employee enrolled.');
        }
    } elseif ($action === 'mark_attendance') {
        // Confirm this enrollment belongs to a program in this org.
        $enrollOwned = $db->fetchOne(
            "SELECT te.id FROM training_enrollment te JOIN training_programs tp ON tp.id=te.training_id WHERE te.id=? AND tp.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([postInt('id')], $orgCompanies)
        );
        if ($enrollOwned) {
            $db->execute("UPDATE training_enrollment SET attendance_status=?,certificate_issued=? WHERE id=?",
                [post('status'), postInt('cert'), postInt('id')]);
            setFlash('success', 'Attendance updated.');
        } else {
            setFlash('error', 'Enrollment not found.');
        }
    }
    $redir = BASE_URL . '/modules/training/index.php';
    if (postInt('prog_id')) $redir .= '?tab=attendance&prog=' . postInt('prog_id');
    header('Location: ' . $redir); exit;
}

$tab      = $_GET['tab'] ?? 'programs';
// FIX: scope programs list to current org.
[$orgClause, $orgParams] = orgScopeClause($db, 'tp.company_id');
$programs = $db->fetchAll("SELECT tp.*, (SELECT COUNT(*) FROM training_enrollment WHERE training_id=tp.id) AS enrolled FROM training_programs tp WHERE $orgClause ORDER BY tp.from_date DESC", $orgParams);
$selProg  = cleanInt($_GET['prog'] ?? 0);
if ($selProg && !in_array($selProg, array_column($programs, 'id'))) { $selProg = 0; }
$enrolls  = $selProg ? $db->fetchAll("SELECT te.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name,e.employee_id AS emp_code FROM training_enrollment te JOIN employees e ON e.id=te.employee_id WHERE te.training_id=? ORDER BY e.first_name", [$selProg]) : [];
[$empOrgClause, $empOrgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id, CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $empOrgClause ORDER BY first_name", $empOrgParams);
$editProg  = cleanInt($_GET['edit'] ?? 0);
if ($editProg && !in_array($editProg, array_column($programs, 'id'))) { $editProg = 0; }
$editData  = $editProg ? $db->fetchOne("SELECT * FROM training_programs WHERE id=?", [$editProg]) : null;
$progInfo  = $selProg ? $db->fetchOne("SELECT * FROM training_programs WHERE id=?", [$selProg]) : null;

include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-tabs mb-3">
  <div class="pc-tab <?=$tab==='programs'?'active':''?>" onclick="location='?tab=programs'">Programs</div>
  <div class="pc-tab <?=$tab==='new'?'active':''?>" onclick="location='?tab=new'">New Program</div>
  <?php if ($selProg): ?>
  <div class="pc-tab <?=$tab==='attendance'?'active':''?>" onclick="location='?tab=attendance&prog=<?=$selProg?>'">Attendance</div>
  <?php endif; ?>
</div>

<?php if ($tab === 'programs'): ?>
<div class="row g-3">
  <?php foreach ($programs as $p): ?>
  <div class="col-md-4">
    <div class="pc-card">
      <div class="d-flex justify-content-between mb-1">
        <span class="fw-bold"><?=clean($p['title'])?></span>
        <?=statusBadge($p['status'])?>
      </div>
      <div class="text-muted small mb-1"><?=ucfirst($p['mode'])?> · <?=clean($p['location'] ?? 'N/A')?></div>
      <div class="small mb-1"><i class="ti ti-calendar me-1"></i><?=fmtDate($p['from_date'])?> → <?=fmtDate($p['to_date'])?></div>
      <div class="small mb-2"><i class="ti ti-clock me-1"></i><?=$p['duration_hours']?> hrs</div>
      <div class="d-flex justify-content-between align-items-center">
        <span class="badge" style="background:var(--pc-blue-bg);color:var(--pc-blue)"><?=$p['enrolled']?>/<?=$p['max_participants']?> enrolled</span>
        <div class="d-flex gap-1">
          <a href="?tab=new&edit=<?=$p['id']?>" class="btn btn-xs btn-outline-primary py-0 px-2">Edit</a>
          <a href="?tab=attendance&prog=<?=$p['id']?>" class="btn btn-xs btn-outline-secondary py-0 px-2">Attendance</a>
        </div>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
  <?php if (!$programs): ?>
  <div class="col"><div class="alert alert-info">No training programs yet. Click New Program to add one.</div></div>
  <?php endif; ?>
</div>

<?php elseif ($tab === 'new'): ?>
<div class="pc-card" style="max-width:650px">
  <div class="pc-card-title"><i class="ti ti-school me-2"></i><?=$editData?'Edit':'New'?> Training Program</div>
  <form method="POST">
    <?=csrfField()?><input type="hidden" name="action" value="save_program">
    <?php if ($editData): ?><input type="hidden" name="id" value="<?=$editData['id']?>"><?php endif; ?>
    <div class="row g-3">
      <div class="col-12">
        <label class="pc-label">Program Title</label>
        <input type="text" name="title" class="form-control form-control-sm" value="<?=clean($editData['title'] ?? '')?>" required>
      </div>
      <div class="col-md-4">
        <label class="pc-label">From Date</label>
        <input type="date" name="from_date" class="form-control form-control-sm" value="<?=clean($editData['from_date'] ?? '')?>" required>
      </div>
      <div class="col-md-4">
        <label class="pc-label">To Date</label>
        <input type="date" name="to_date" class="form-control form-control-sm" value="<?=clean($editData['to_date'] ?? '')?>" required>
      </div>
      <div class="col-md-4">
        <label class="pc-label">Duration (hrs)</label>
        <input type="number" name="hours" class="form-control form-control-sm" value="<?=(int)($editData['duration_hours'] ?? 8)?>">
      </div>
      <div class="col-md-4">
        <label class="pc-label">Mode</label>
        <select name="mode" class="form-select form-select-sm">
          <?php foreach (['classroom','online','hybrid'] as $m): ?>
          <option value="<?=$m?>" <?=($editData['mode'] ?? '') === $m ? 'selected' : ''?>><?=ucfirst($m)?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4">
        <label class="pc-label">Location / Venue</label>
        <input type="text" name="location" class="form-control form-control-sm" value="<?=clean($editData['location'] ?? '')?>">
      </div>
      <div class="col-md-4">
        <label class="pc-label">Max Participants</label>
        <input type="number" name="max_p" class="form-control form-control-sm" value="<?=(int)($editData['max_participants'] ?? 20)?>">
      </div>
      <?php if ($editData): ?>
      <div class="col-md-4">
        <label class="pc-label">Status</label>
        <select name="status" class="form-select form-select-sm">
          <?php foreach (['planned','active','completed','cancelled'] as $s): ?>
          <option value="<?=$s?>" <?=($editData['status'] ?? '') === $s ? 'selected' : ''?>><?=ucfirst($s)?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php endif; ?>
      <div class="col-12">
        <label class="pc-label">Description</label>
        <textarea name="description" class="form-control form-control-sm" rows="3"><?=clean($editData['description'] ?? '')?></textarea>
      </div>
    </div>
    <div class="mt-3 d-flex gap-2">
      <button class="btn btn-pc">Save Program</button>
      <a href="?tab=programs" class="btn btn-outline-secondary">Cancel</a>
    </div>
  </form>
</div>

<?php elseif ($tab === 'attendance' && $selProg): ?>
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card mb-3">
      <div class="pc-card-title">Enroll Employee</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="enroll">
        <input type="hidden" name="prog_id" value="<?=$selProg?>">
        <div class="mb-3">
          <label class="pc-label">Employee</label>
          <select name="emp_id" class="form-select form-select-sm" required>
            <option value="">Select</option>
            <?php foreach ($employees as $e): ?>
            <option value="<?=$e['id']?>"><?=clean($e['label'])?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-user-plus me-1"></i>Enroll</button>
      </form>
    </div>
    <?php if ($progInfo): ?>
    <div class="pc-card">
      <div class="fw-bold mb-2"><?=clean($progInfo['title'])?></div>
      <div class="small text-muted"><?=fmtDate($progInfo['from_date'])?> → <?=fmtDate($progInfo['to_date'])?></div>
      <div class="small text-muted"><?=$progInfo['duration_hours']?> hrs · <?=ucfirst($progInfo['mode'])?></div>
      <div class="small text-muted mt-1"><?=clean($progInfo['location'] ?? '')?></div>
    </div>
    <?php endif; ?>
  </div>
  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title">Enrollments & Attendance</div>
      <table class="pc-table">
        <thead>
          <tr><th>Employee</th><th>Enrolled</th><th>Status</th><th>Certificate</th><th>Score</th><th>Update</th></tr>
        </thead>
        <tbody>
        <?php foreach ($enrolls as $en): ?>
        <tr>
          <td>
            <div class="fw-semibold"><?=clean($en['emp_name'])?></div>
            <small class="text-muted"><?=clean($en['emp_code'])?></small>
          </td>
          <td><?=fmtDate($en['enrolled_date'])?></td>
          <td><?=statusBadge($en['attendance_status'])?></td>
          <td><?=$en['certificate_issued'] ? '<i class="ti ti-certificate text-success"></i> Yes' : '—'?></td>
          <td><?=$en['score'] > 0 ? $en['score'].'%' : '—'?></td>
          <td>
            <form method="POST">
              <?=csrfField()?><input type="hidden" name="action" value="mark_attendance">
              <input type="hidden" name="id" value="<?=$en['id']?>">
              <input type="hidden" name="prog_id" value="<?=$selProg?>">
              <div class="d-flex gap-1">
                <select name="status" class="form-select form-select-sm" style="width:105px">
                  <?php foreach (['enrolled','attended','completed','absent'] as $s): ?>
                  <option value="<?=$s?>" <?=$en['attendance_status']===$s?'selected':''?>><?=ucfirst($s)?></option>
                  <?php endforeach; ?>
                </select>
                <div class="form-check align-self-center ms-1">
                  <input type="checkbox" name="cert" value="1" class="form-check-input" id="cert_<?=$en['id']?>" <?=$en['certificate_issued']?'checked':''?>>
                  <label class="form-check-label small" for="cert_<?=$en['id']?>">Cert</label>
                </div>
                <button class="btn btn-xs btn-pc py-0 px-2">Save</button>
              </div>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (!$enrolls): ?>
        <tr><td colspan="6" class="text-center text-muted py-3">No enrollments yet</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php endif; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>