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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = post('action');
    // FIX (07 Jul 2026): appraisal_cycles had no org concept at all —
    // added company_id (migration_appraisal_cycles_company.sql) and
    // scoped everything below to the current org.
    $orgCompanies = orgCompanyIds($db);
    $companyId    = $orgCompanies[0] ?? 0;
    if ($action === 'save_cycle') {
        $id = postInt('id');
        if ($id) {
            $owned = $db->fetchOne("SELECT id FROM appraisal_cycles WHERE id=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")", array_merge([$id], $orgCompanies));
            if (!$owned) { setFlash('error','Cycle not found.'); header('Location: ' . BASE_URL . '/modules/appraisal/index.php'); exit; }
            $db->execute("UPDATE appraisal_cycles SET name=?,from_date=?,to_date=?,review_date=?,status=? WHERE id=?",
                [post('name'),post('from_date'),post('to_date'),post('review_date'),post('status'),$id]);
        } else {
            $db->execute("INSERT INTO appraisal_cycles (company_id,name,from_date,to_date,review_date,status,created_by) VALUES (?,?,?,?,?,?,?)",
                [$companyId,post('name'),post('from_date'),post('to_date'),post('review_date'),'active',currentUser()['id']]);
        }
        setFlash('success','Appraisal cycle saved.');
    } elseif ($action === 'save_review') {
        $id = postInt('id');
        $empId = postInt('employee_id');
        if ($id) {
            // Confirm the review being edited belongs to a cycle in this org.
            $owned = $db->fetchOne(
                "SELECT r.id FROM appraisal_reviews r JOIN appraisal_cycles c ON c.id=r.appraisal_cycle_id WHERE r.id=? AND c.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
                array_merge([$id], $orgCompanies)
            );
            if (!$owned) { setFlash('error','Review not found.'); header('Location: ' . BASE_URL . '/modules/appraisal/index.php'); exit; }
            $db->execute("UPDATE appraisal_reviews SET self_rating=?,manager_rating=?,final_rating=?,self_comments=?,manager_comments=?,status=? WHERE id=?",
                [post('self_rating')?:null, post('mgr_rating')?:null, post('final_rating')?:null, post('self_comments'), post('mgr_comments'), post('status'), $id]);
        } else {
            // Confirm target employee belongs to current org.
            $target = $db->fetchOne("SELECT company_id FROM employees WHERE id=?", [$empId]);
            if (!$target || !in_array($target['company_id'], $orgCompanies)) {
                setFlash('error', 'Employee not found.');
                header('Location: ' . BASE_URL . '/modules/appraisal/index.php'); exit;
            }
            $db->execute("INSERT INTO appraisal_reviews (appraisal_cycle_id,employee_id,reviewer_id,self_rating,self_comments,status) VALUES (?,?,?,?,?,'draft')",
                [postInt('cycle_id'), $empId, currentUser()['id'], post('self_rating')?:null, post('self_comments')]);
        }
        setFlash('success','Review saved.');
    }
    header('Location: ' . BASE_URL . '/modules/appraisal/index.php'); exit;
}

$tab       = $_GET['tab'] ?? 'cycles';
// FIX: scope cycles list to current org.
[$orgClause, $orgParams] = orgScopeClause($db, 'c.company_id');
$cycles    = $db->fetchAll("SELECT c.*, (SELECT COUNT(*) FROM appraisal_reviews WHERE appraisal_cycle_id=c.id) AS review_count FROM appraisal_cycles c WHERE $orgClause ORDER BY c.created_at DESC", $orgParams);
$selCycle  = cleanInt($_GET['cycle'] ?? 0);
if ($selCycle && !in_array($selCycle, array_column($cycles, 'id'))) { $selCycle = 0; }
$reviews   = $selCycle ? $db->fetchAll("SELECT r.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name,e.employee_id AS emp_code,des.name AS designation FROM appraisal_reviews r JOIN employees e ON e.id=r.employee_id LEFT JOIN designations des ON des.id=e.designation_id WHERE r.appraisal_cycle_id=? ORDER BY e.first_name", [$selCycle]) : [];
[$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);
$editCycle = cleanInt($_GET['edit'] ?? 0);
if ($editCycle && !in_array($editCycle, array_column($cycles, 'id'))) { $editCycle = 0; }
$editData  = $editCycle ? $db->fetchOne("SELECT * FROM appraisal_cycles WHERE id=?", [$editCycle]) : null;
$ratings   = [1=>'1 - Poor', 2=>'2 - Below Average', 3=>'3 - Average', 4=>'4 - Good', 5=>'5 - Excellent'];

include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-tabs mb-3">
  <div class="pc-tab <?=$tab==='cycles'?'active':''?>" onclick="location='?tab=cycles'">Appraisal Cycles</div>
  <div class="pc-tab <?=$tab==='new_cycle'?'active':''?>" onclick="location='?tab=new_cycle'">New Cycle</div>
  <?php if ($selCycle): ?>
  <div class="pc-tab <?=$tab==='reviews'?'active':''?>" onclick="location='?tab=reviews&cycle=<?=$selCycle?>'">Reviews</div>
  <?php endif; ?>
</div>

<?php if ($tab === 'cycles'): ?>
<div class="row g-3">
  <?php foreach ($cycles as $c): ?>
  <div class="col-md-4">
    <div class="pc-card">
      <div class="fw-bold mb-1"><?=clean($c['name'])?></div>
      <div class="text-muted small mb-2"><?=fmtDate($c['from_date'])?> → <?=fmtDate($c['to_date'])?></div>
      <div class="d-flex justify-content-between align-items-center">
        <?=statusBadge($c['status'])?>
        <span class="badge" style="background:var(--pc-blue-bg);color:var(--pc-blue)"><?=$c['review_count']?> Reviews</span>
      </div>
      <div class="mt-2 d-flex gap-2">
        <a href="?tab=new_cycle&edit=<?=$c['id']?>" class="btn btn-xs btn-outline-primary py-0 px-2">Edit</a>
        <a href="?tab=reviews&cycle=<?=$c['id']?>" class="btn btn-xs btn-outline-secondary py-0 px-2">View Reviews</a>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
  <?php if (!$cycles): ?>
  <div class="col"><div class="alert alert-info">No appraisal cycles created yet.</div></div>
  <?php endif; ?>
</div>

<?php elseif ($tab === 'new_cycle'): ?>
<div class="pc-card" style="max-width:500px">
  <div class="pc-card-title"><i class="ti ti-trophy me-2"></i><?=$editData?'Edit':'New'?> Appraisal Cycle</div>
  <form method="POST">
    <?=csrfField()?><input type="hidden" name="action" value="save_cycle">
    <?php if ($editData): ?><input type="hidden" name="id" value="<?=$editData['id']?>"><?php endif; ?>
    <div class="mb-2"><label class="pc-label">Cycle Name</label>
      <input type="text" name="name" class="form-control form-control-sm" value="<?=clean($editData['name'] ?? '')?>" placeholder="e.g. Annual Review 2025" required></div>
    <div class="row g-2 mb-2">
      <div class="col"><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"><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>
    <div class="mb-2"><label class="pc-label">Review Deadline</label>
      <input type="date" name="review_date" class="form-control form-control-sm" value="<?=clean($editData['review_date'] ?? '')?>"></div>
    <?php if ($editData): ?>
    <div class="mb-3"><label class="pc-label">Status</label>
      <select name="status" class="form-select form-select-sm">
        <?php foreach (['active','completed','cancelled'] as $s): ?>
        <option value="<?=$s?>" <?=$editData['status']===$s?'selected':''?>><?=ucfirst($s)?></option>
        <?php endforeach; ?>
      </select></div>
    <?php endif; ?>
    <div class="d-flex gap-2">
      <button class="btn btn-pc">Save Cycle</button>
      <a href="?tab=cycles" class="btn btn-outline-secondary">Cancel</a>
    </div>
  </form>
</div>

<?php elseif ($tab === 'reviews' && $selCycle):
  $cycleInfo = $db->fetchOne("SELECT * FROM appraisal_cycles WHERE id=?", [$selCycle]);
?>
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card mb-3">
      <div class="pc-card-title">Add Review</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="save_review">
        <input type="hidden" name="cycle_id" value="<?=$selCycle?>">
        <div class="mb-2"><label class="pc-label">Employee</label>
          <select name="employee_id" class="form-select form-select-sm">
            <option value="">Select</option>
            <?php foreach ($employees as $e): ?>
            <option value="<?=$e['id']?>"><?=clean($e['label'])?></option>
            <?php endforeach; ?>
          </select></div>
        <div class="mb-2"><label class="pc-label">Self Rating</label>
          <select name="self_rating" class="form-select form-select-sm">
            <option value="">--</option>
            <?php foreach ($ratings as $v=>$l): ?><option value="<?=$v?>"><?=$l?></option><?php endforeach; ?>
          </select></div>
        <div class="mb-3"><label class="pc-label">Self Comments</label>
          <textarea name="self_comments" class="form-control form-control-sm" rows="2"></textarea></div>
        <button class="btn btn-pc btn-sm w-100">Add Review</button>
      </form>
    </div>
  </div>
  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title"><?=clean($cycleInfo['name'] ?? '')?> — Reviews</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Employee</th><th>Self</th><th>Manager</th><th>Final</th><th>Status</th><th>Update</th></tr></thead>
          <tbody>
          <?php foreach ($reviews as $r): ?>
          <tr>
            <td>
              <div class="fw-semibold"><?=clean($r['emp_name'])?></div>
              <small class="text-muted"><?=clean($r['designation'] ?? '')?></small>
            </td>
            <td>
              <?php if ($r['self_rating']): ?>
                <span class="fw-bold" style="color:var(--pc-amber)"><?=str_repeat('★', $r['self_rating'])?></span>
              <?php else: ?>—<?php endif; ?>
            </td>
            <td>
              <?php if ($r['manager_rating']): ?>
                <span class="fw-bold" style="color:var(--pc-green)"><?=str_repeat('★', $r['manager_rating'])?></span>
              <?php else: ?>—<?php endif; ?>
            </td>
            <td><?=clean($r['final_rating'] ?? '—')?></td>
            <td><?=statusBadge($r['status'])?></td>
            <td>
              <form method="POST">
                <?=csrfField()?>
                <input type="hidden" name="action" value="save_review">
                <input type="hidden" name="id" value="<?=$r['id']?>">
                <input type="hidden" name="self_rating" value="<?=(int)$r['self_rating']?>">
                <input type="hidden" name="self_comments" value="<?=clean($r['self_comments'] ?? '')?>">
                <div class="d-flex gap-1 mb-1">
                  <input type="number" name="mgr_rating" class="form-control form-control-sm" style="width:55px" min="1" max="5" placeholder="Mgr" value="<?=(int)$r['manager_rating'] ?: ''?>">
                  <input type="number" name="final_rating" class="form-control form-control-sm" style="width:55px" min="1" max="5" placeholder="Final" value="<?=(int)$r['final_rating'] ?: ''?>">
                  <select name="status" class="form-select form-select-sm" style="width:90px">
                    <?php foreach (['draft','submitted','reviewed','completed'] as $s): ?>
                    <option value="<?=$s?>" <?=$r['status']===$s?'selected':''?>><?=ucfirst($s)?></option>
                    <?php endforeach; ?>
                  </select>
                  <button class="btn btn-xs btn-pc py-0 px-2">Save</button>
                </div>
                <textarea name="mgr_comments" class="form-control form-control-sm" rows="1" placeholder="Manager comments"><?=clean($r['manager_comments'] ?? '')?></textarea>
              </form>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (!$reviews): ?>
          <tr><td colspan="6" class="text-center text-muted py-3">No reviews yet</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>