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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';
    if ($action === 'save' || $action === 'submit') {
        $empId = $user['emp_id'] ?: postInt('employee_id');
        $weekStart = post('week_start');
        $weekEnd   = date('Y-m-d', strtotime($weekStart . ' +6 days'));
        $status = ($action === 'submit') ? 'submitted' : 'draft';
        $existing = $db->fetchOne("SELECT id FROM timesheets WHERE employee_id=? AND week_start=?", [$empId, $weekStart]);
        if ($existing) {
            $db->execute("UPDATE timesheets SET status=?,submitted_at=? WHERE id=?", [$status, $action==='submit'?date('Y-m-d H:i:s'):null, $existing['id']]);
            $tsId = $existing['id'];
            $db->execute("DELETE FROM timesheet_entries WHERE timesheet_id=?", [$tsId]);
        } else {
            $db->execute("INSERT INTO timesheets (employee_id,week_start,week_end,status,submitted_at) VALUES (?,?,?,?,?)",
                [$empId,$weekStart,$weekEnd,$status,$action==='submit'?date('Y-m-d H:i:s'):null]);
            $tsId = $db->lastInsertId();
        }
        $dates   = $_POST['entry_date']   ?? [];
        $projects= $_POST['project']      ?? [];
        $tasks   = $_POST['task']         ?? [];
        $hours   = $_POST['hours']        ?? [];
        $descs   = $_POST['description']  ?? [];
        $total = 0;
        foreach($dates as $i => $d) {
            if (!$d || !($hours[$i]??0)) continue;
            $h = floatval($hours[$i]);
            $total += $h;
            $db->execute("INSERT INTO timesheet_entries (timesheet_id,entry_date,project,task,hours,description) VALUES (?,?,?,?,?,?)",
                [$tsId,$d,$projects[$i]??'',$tasks[$i]??'',$h,$descs[$i]??'']);
        }
        $db->execute("UPDATE timesheets SET total_hours=? WHERE id=?", [$total,$tsId]);
        setFlash('success', $action==='submit'?'Timesheet submitted for approval.':'Timesheet saved as draft.');
    } elseif ($action === 'approve' || $action === 'reject') {
        // FIX (07 Jul 2026): confirm this timesheet belongs to an employee
        // in the current organization before approving/rejecting it.
        $orgCompanies = orgCompanyIds($db);
        $tsOwner = $db->fetchOne(
            "SELECT t.id FROM timesheets t JOIN employees e ON e.id=t.employee_id WHERE t.id=? AND e.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([postInt('id')], $orgCompanies)
        );
        if (!$tsOwner) {
            setFlash('error', 'Timesheet not found.');
        } elseif ($action === 'approve') {
            $db->execute("UPDATE timesheets SET status='approved',approved_by=? WHERE id=?", [$user['id'], postInt('id')]);
            setFlash('success','Timesheet approved.');
        } else {
            $db->execute("UPDATE timesheets SET status='rejected' WHERE id=?", [postInt('id')]);
            setFlash('success','Timesheet rejected.');
        }
    }
    header('Location: '.BASE_URL.'/modules/attendance/timesheet.php'); exit;
}

$weekStart = $_GET['week'] ?? date('Y-m-d', strtotime('monday this week'));
$weekEnd   = date('Y-m-d', strtotime($weekStart.' +6 days'));
$empId     = $user['emp_id'];
// FIX: scope dropdown/list/lookup to current org.
[$orgClause, $orgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id, CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $orgClause ORDER BY first_name", $orgParams);
$selEmpId  = cleanInt($_GET['emp'] ?? ($empId ?: 0));
if ($selEmpId && !in_array($selEmpId, array_column($employees, 'id'))) { $selEmpId = 0; }

$ts      = $selEmpId ? $db->fetchOne("SELECT * FROM timesheets WHERE employee_id=? AND week_start=?", [$selEmpId,$weekStart]) : null;
$entries = $ts ? $db->fetchAll("SELECT * FROM timesheet_entries WHERE timesheet_id=? ORDER BY entry_date", [$ts['id']]) : [];
$entryMap = [];
foreach($entries as $en) $entryMap[$en['entry_date']] = $en;

[$allTsClause, $allTsParams] = orgScopeClause($db, 'e.company_id');
$allTs = $db->fetchAll("SELECT t.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name FROM timesheets t JOIN employees e ON e.id=t.employee_id WHERE $allTsClause ORDER BY t.week_start DESC LIMIT 30", $allTsParams);

// Build week days
$days = [];
for($i=0;$i<7;$i++) $days[] = date('Y-m-d', strtotime($weekStart." +$i days"));

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-lg-8">
    <div class="pc-card mb-3">
      <div class="d-flex align-items-center gap-2 mb-3">
        <a href="?week=<?=date('Y-m-d',strtotime($weekStart.' -7 days'))?>&emp=<?=$selEmpId?>" class="btn btn-sm btn-outline-secondary"><i class="ti ti-chevron-left"></i></a>
        <strong>Week: <?=date('d M',strtotime($weekStart))?> – <?=date('d M Y',strtotime($weekEnd))?></strong>
        <a href="?week=<?=date('Y-m-d',strtotime($weekStart.' +7 days'))?>&emp=<?=$selEmpId?>" class="btn btn-sm btn-outline-secondary"><i class="ti ti-chevron-right"></i></a>
        <a href="?week=<?=date('Y-m-d',strtotime('monday this week'))?>&emp=<?=$selEmpId?>" class="btn btn-sm btn-outline-primary ms-1">Today</a>
        <div class="ms-auto">
          <select class="form-select form-select-sm" style="width:220px" onchange="location='?week=<?=$weekStart?>&emp='+this.value">
            <option value="">Select Employee</option>
            <?php foreach($employees as $e): ?><option value="<?=$e['id']?>" <?=$selEmpId==$e['id']?'selected':''?>><?=clean($e['label'])?></option><?php endforeach; ?>
          </select>
        </div>
      </div>

      <?php if($ts): ?>
      <div class="alert alert-<?=$ts['status']==='approved'?'success':($ts['status']==='submitted'?'info':'warning')?> py-2 small mb-3">
        Status: <strong><?=ucfirst($ts['status'])?></strong> | Total: <strong><?=$ts['total_hours']?> hrs</strong>
      </div>
      <?php endif; ?>

      <form method="POST">
        <?=csrfField()?>
        <input type="hidden" name="week_start" value="<?=$weekStart?>">
        <?php if(!$empId): ?><input type="hidden" name="employee_id" value="<?=$selEmpId?>"><?php endif; ?>
        <div class="pc-table-wrap">
          <table class="pc-table">
            <thead><tr><th>Date</th><th>Project</th><th>Task</th><th>Hours</th><th>Notes</th></tr></thead>
            <tbody>
            <?php foreach($days as $day):
              $dayName = date('D', strtotime($day));
              $isWeekend = in_array($dayName, ['Sat','Sun']);
              $en = $entryMap[$day] ?? null;
            ?>
            <tr style="background:<?=$isWeekend?'#f5f8fc':'white'?>">
              <td><strong><?=date('D, d M', strtotime($day))?></strong><?php if($isWeekend): ?><br><small class="text-muted">Weekend</small><?php endif; ?></td>
              <td><input type="hidden" name="entry_date[]" value="<?=$day?>"><input type="text" name="project[]" class="form-control form-control-sm" value="<?=clean($en['project']??'')?>" placeholder="Project"></td>
              <td><input type="text" name="task[]" class="form-control form-control-sm" value="<?=clean($en['task']??'')?>" placeholder="Task"></td>
              <td style="width:70px"><input type="number" name="hours[]" class="form-control form-control-sm" value="<?=$en['hours']??0?>" min="0" max="24" step="0.5"></td>
              <td><input type="text" name="description[]" class="form-control form-control-sm" value="<?=clean($en['description']??'')?>" placeholder="Notes"></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <div class="mt-3 d-flex gap-2">
          <?php if(!$ts || $ts['status']==='draft' || $ts['status']==='rejected'): ?>
          <button name="action" value="save" class="btn btn-outline-secondary btn-sm"><i class="ti ti-device-floppy me-1"></i>Save Draft</button>
          <button name="action" value="submit" class="btn btn-pc btn-sm"><i class="ti ti-send me-1"></i>Submit for Approval</button>
          <?php endif; ?>
        </div>
      </form>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="pc-card">
      <div class="pc-card-title">Recent Timesheets</div>
      <?php foreach($allTs as $t): ?>
      <div class="d-flex justify-content-between align-items-center py-2 border-bottom" style="font-size:12px">
        <div>
          <div class="fw-semibold"><?=clean($t['emp_name'])?></div>
          <div class="text-muted">Week of <?=date('d M',strtotime($t['week_start']))?> · <?=$t['total_hours']?> hrs</div>
        </div>
        <div class="d-flex gap-1 align-items-center">
          <?=statusBadge($t['status'])?>
          <?php if($t['status']==='submitted'): ?>
          <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="approve"><input type="hidden" name="id" value="<?=$t['id']?>"><button class="btn btn-xs btn-success py-0 px-1" style="font-size:10px">✓</button></form>
          <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="reject"><input type="hidden" name="id" value="<?=$t['id']?>"><button class="btn btn-xs btn-danger py-0 px-1" style="font-size:10px">✗</button></form>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>