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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $empId = postInt('employee_id');
    // FIX (07 Jul 2026): confirm this employee belongs to the current org
    // before updating — otherwise anyone logged in could POST an arbitrary
    // employee_id belonging to a different organization.
    $target = $db->fetchOne("SELECT company_id FROM employees WHERE id=?", [$empId]);
    if (!$target || !in_array($target['company_id'], orgCompanyIds($db))) {
        setFlash('error', 'Employee not found.');
        header('Location: '.BASE_URL.'/modules/employees/assign.php'); exit;
    }
    $db->execute("UPDATE employees SET department_id=?,designation_id=?,grade_id=?,shift_id=?,reporting_manager_id=?,location_id=?,branch_id=?,employment_type=?,work_type=? WHERE id=?",
        [postInt('department_id'),postInt('designation_id'),postInt('grade_id'),postInt('shift_id'),postInt('reporting_manager_id')?:null,postInt('location_id'),postInt('branch_id'),post('employment_type'),post('work_type'),$empId]);
    setFlash('success','Employee assignment updated successfully.');
    header('Location: '.BASE_URL.'/modules/employees/assign.php?emp='.$empId); exit;
}

$selEmp    = cleanInt($_GET['emp'] ?? 0);
[$assignOrgClause, $assignOrgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id, CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $assignOrgClause ORDER BY first_name", $assignOrgParams);
$depts     = $db->fetchAll("SELECT id,name FROM departments WHERE is_active=1 ORDER BY name");
$desigs    = $db->fetchAll("SELECT id,name FROM designations WHERE is_active=1 ORDER BY name");
$grades    = $db->fetchAll("SELECT id,name FROM grades WHERE is_active=1 ORDER BY name");
$shifts    = $db->fetchAll("SELECT id,name FROM shifts WHERE is_active=1 ORDER BY name");
$locations = $db->fetchAll("SELECT id,name FROM locations WHERE is_active=1 ORDER BY name");
$branches  = $db->fetchAll("SELECT id,name FROM branches WHERE is_active=1 ORDER BY name");
$managers  = $employees;
// FIX: don't leak another org's employee via ?emp=<id> in the URL.
$emp       = ($selEmp && in_array($selEmp, array_column($employees,'id')))
             ? $db->fetchOne("SELECT e.*,d.name AS dept_name,des.name AS desig_name,g.name AS grade_name,s.name AS shift_name,l.name AS loc_name,CONCAT(m.first_name,' ',m.last_name) AS manager_name FROM employees e LEFT JOIN departments d ON d.id=e.department_id LEFT JOIN designations des ON des.id=e.designation_id LEFT JOIN grades g ON g.id=e.grade_id LEFT JOIN shifts s ON s.id=e.shift_id LEFT JOIN locations l ON l.id=e.location_id LEFT JOIN employees m ON m.id=e.reporting_manager_id WHERE e.id=?", [$selEmp])
             : null;

include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-card mb-3">
  <form method="GET" class="d-flex gap-2 align-items-end">
    <div><label class="pc-label">Select Employee</label>
      <select name="emp" class="form-select form-select-sm" style="width:300px" onchange="this.form.submit()">
        <option value="">-- Select Employee --</option>
        <?php foreach($employees as $e): ?><option value="<?=$e['id']?>" <?=$selEmp==$e['id']?'selected':''?>><?=clean($e['label'])?></option><?php endforeach; ?>
      </select></div>
  </form>
</div>

<?php if($emp): ?>
<div class="row g-3">
  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-clipboard-list me-2"></i>Assignment Details — <?=clean($emp['first_name'].' '.$emp['last_name'])?></div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="employee_id" value="<?=$selEmp?>">
        <div class="row g-3">
          <div class="col-md-6"><label class="pc-label">Department</label>
            <select name="department_id" class="form-select form-select-sm"><option value="">Select</option><?php foreach($depts as $d): ?><option value="<?=$d['id']?>" <?=$emp['department_id']==$d['id']?'selected':''?>><?=clean($d['name'])?></option><?php endforeach; ?></select></div>
          <div class="col-md-6"><label class="pc-label">Designation</label>
            <select name="designation_id" class="form-select form-select-sm"><option value="">Select</option><?php foreach($desigs as $d): ?><option value="<?=$d['id']?>" <?=$emp['designation_id']==$d['id']?'selected':''?>><?=clean($d['name'])?></option><?php endforeach; ?></select></div>
          <div class="col-md-6"><label class="pc-label">Grade</label>
            <select name="grade_id" class="form-select form-select-sm"><option value="">Select</option><?php foreach($grades as $g): ?><option value="<?=$g['id']?>" <?=$emp['grade_id']==$g['id']?'selected':''?>><?=clean($g['name'])?></option><?php endforeach; ?></select></div>
          <div class="col-md-6"><label class="pc-label">Shift</label>
            <select name="shift_id" class="form-select form-select-sm"><option value="">Select</option><?php foreach($shifts as $s): ?><option value="<?=$s['id']?>" <?=$emp['shift_id']==$s['id']?'selected':''?>><?=clean($s['name'])?></option><?php endforeach; ?></select></div>
          <div class="col-md-6"><label class="pc-label">Location</label>
            <select name="location_id" class="form-select form-select-sm"><option value="">Select</option><?php foreach($locations as $l): ?><option value="<?=$l['id']?>" <?=$emp['location_id']==$l['id']?'selected':''?>><?=clean($l['name'])?></option><?php endforeach; ?></select></div>
          <div class="col-md-6"><label class="pc-label">Branch</label>
            <select name="branch_id" class="form-select form-select-sm"><option value="">Select</option><?php foreach($branches as $b): ?><option value="<?=$b['id']?>" <?=$emp['branch_id']==$b['id']?'selected':''?>><?=clean($b['name'])?></option><?php endforeach; ?></select></div>
          <div class="col-md-6"><label class="pc-label">Reporting Manager</label>
            <select name="reporting_manager_id" class="form-select form-select-sm"><option value="">None</option><?php foreach($managers as $m): if($m['id']==$selEmp) continue; ?><option value="<?=$m['id']?>" <?=$emp['reporting_manager_id']==$m['id']?'selected':''?>><?=clean($m['label'])?></option><?php endforeach; ?></select></div>
          <div class="col-md-3"><label class="pc-label">Employment Type</label>
            <select name="employment_type" class="form-select form-select-sm"><?php foreach(['permanent','probation','contract','intern'] as $et): ?><option value="<?=$et?>" <?=$emp['employment_type']===$et?'selected':''?>><?=ucfirst($et)?></option><?php endforeach; ?></select></div>
          <div class="col-md-3"><label class="pc-label">Work Type</label>
            <select name="work_type" class="form-select form-select-sm"><?php foreach(['full_time','part_time','contract'] as $wt): ?><option value="<?=$wt?>" <?=$emp['work_type']===$wt?'selected':''?>><?=ucwords(str_replace('_',' ',$wt))?></option><?php endforeach; ?></select></div>
        </div>
        <div class="mt-3"><button class="btn btn-pc"><i class="ti ti-device-floppy me-1"></i>Save Assignment</button></div>
      </form>
    </div>
  </div>
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title">Current Assignment</div>
      <?php $rows=[['Department',$emp['dept_name']??'—'],['Designation',$emp['desig_name']??'—'],['Grade',$emp['grade_name']??'—'],['Shift',$emp['shift_name']??'—'],['Location',$emp['loc_name']??'—'],['Manager',$emp['manager_name']??'—'],['Employment',ucfirst($emp['employment_type']??'—')],['Work Type',ucwords(str_replace('_',' ',$emp['work_type']??'—'))]];
      foreach($rows as [$k,$v]): ?>
      <div class="d-flex justify-content-between py-2 border-bottom" style="font-size:12.5px">
        <span class="text-muted"><?=$k?></span><span class="fw-semibold"><?=clean($v)?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php endif; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>