<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_login();

$pdo = db();
$cid = (int)$_SESSION['company_id'];

$err = null;
$openModal = false;

$emps = $pdo->prepare("SELECT id, full_name FROM employees WHERE company_id=? AND status='ACTIVE' ORDER BY full_name");
$emps->execute([$cid]);
$emps = $emps->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $employee_id = (int)($_POST['employee_id'] ?? 0);
  $mission_date = $_POST['mission_date'] ?? date('Y-m-d');
  $title = trim($_POST['title'] ?? '');
  $location = trim($_POST['location'] ?? '');
  $from_time = $_POST['from_time'] ?? null;
  $to_time = $_POST['to_time'] ?? null;
  $allowance = (float)($_POST['allowance'] ?? 0);
  $notes = trim($_POST['notes'] ?? '');

  if (!$employee_id) $err = 'اختر الموظف';
  if ($title === '') $err = 'عنوان المأمورية مطلوب';

  if (!$err) {
    $st = $pdo->prepare("INSERT INTO missions (company_id, employee_id, mission_date, title, location, from_time, to_time, allowance, notes)
                         VALUES (?,?,?,?,?,?,?,?,?)");
    $st->execute([$cid, $employee_id, $mission_date, $title, $location?:null, $from_time?:null, $to_time?:null, $allowance, $notes?:null]);
    flash_set('تم تسجيل المأمورية بنجاح');
    header('Location: missions.php');
    exit;
  }
  $openModal = true;
}

$rows = $pdo->prepare("SELECT m.*, e.full_name FROM missions m JOIN employees e ON e.id=m.employee_id
                       WHERE m.company_id=? ORDER BY m.mission_date DESC, m.id DESC LIMIT 200");
$rows->execute([$cid]);
$rows = $rows->fetchAll(PDO::FETCH_ASSOC);

render_layout('المأموريات','الموارد البشرية <span class="mx-1">/</span> المأموريات', function() use ($emps,$rows,$err,$openModal) {
?>
<div class="container-fluid mt-3">
  <div class="d-flex align-items-start align-items-md-center justify-content-between flex-column flex-md-row gap-2 mb-3">
    <div>
      <div class="fw-bold fs-4">المأموريات</div>
      <div class="text-secondary small">تسجيل مأموريات الموظفين من خلال نافذة منبثقة داخل الصفحة.</div>
    </div>
    <button class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#missionCreateModal"><i class="bi bi-plus-lg"></i> إضافة مأمورية</button>
  </div>

  <?php if($err): ?>
    <div class="alert alert-danger"><?= h($err) ?></div>
  <?php endif; ?>

  <div class="card cardx">
    <div class="p-3 d-flex align-items-center justify-content-between">
      <div class="fw-bold">آخر المأموريات</div>
      <span class="text-secondary small">آخر 200</span>
    </div>
    <div class="table-responsive px-3 pb-3">
      <table class="table align-middle mb-0">
        <thead>
          <tr class="text-secondary small">
            <th>#</th><th>الموظف</th><th>التاريخ</th><th>العنوان</th><th class="text-end">بدل</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($rows as $r): ?>
            <tr>
              <td class="text-secondary"><?= (int)$r['id'] ?></td>
              <td class="fw-semibold"><?= h($r['full_name']) ?></td>
              <td class="text-secondary"><?= h($r['mission_date']) ?></td>
              <td><?= h($r['title']) ?> <span class="text-secondary small"><?= h($r['location'] ?? '') ?></span></td>
              <td class="text-end"><?= number_format((float)$r['allowance'],2) ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if(!count($rows)): ?>
            <tr><td colspan="5" class="text-center text-secondary py-4">لا توجد مأموريات</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade modal-erp" id="missionCreateModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post">
        <?= csrf_field() ?>
        <div class="modal-header">
          <h5 class="modal-title">إضافة مأمورية</h5>
          <button type="button" class="btn-close m-0" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="row g-3 modal-inline-grid">
            <div class="col-md-6">
              <label class="form-label">الموظف</label>
              <div class="picker-with-action"><select class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" required id="employee_id" name="employee_id" title="اختر الموظف">
                <?php foreach($emps as $e): ?>
                  <option value="<?= (int)$e['id'] ?>" <?= ((int)($e['id']) === (int)($_POST['employee_id'] ?? 0)) ? 'selected' : '' ?>><?= h($e['full_name']) ?></option>
                <?php endforeach; ?>
              </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="employee" data-target="#employee_id" title="إضافة موظف"><i class="bi bi-plus-lg"></i></button></div>
            </div>
            <div class="col-md-6">
              <label class="form-label">التاريخ</label>
              <?= render_date_input('mission_date', $_POST['mission_date'] ?? date('Y-m-d')) ?>
            </div>
            <div class="col-12">
              <label class="form-label">العنوان</label>
              <input class="form-control" name="title" required value="<?= h($_POST['title'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">المكان</label>
              <input class="form-control" name="location" value="<?= h($_POST['location'] ?? '') ?>">
            </div>
            <div class="col-md-3">
              <label class="form-label">من</label>
              <input class="form-control" type="time" name="from_time" value="<?= h($_POST['from_time'] ?? '') ?>">
            </div>
            <div class="col-md-3">
              <label class="form-label">إلى</label>
              <input class="form-control" type="time" name="to_time" value="<?= h($_POST['to_time'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">بدل مأمورية (اختياري)</label>
              <input class="form-control" type="number" step="0.01" name="allowance" value="<?= h($_POST['allowance'] ?? '0') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">ملاحظات</label>
              <input class="form-control" name="notes" value="<?= h($_POST['notes'] ?? '') ?>">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark"><i class="bi bi-check2-circle"></i> حفظ</button>
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إغلاق</button>
        </div>
      </form>
    </div>
  </div>
</div>
<script>window.quickSources = window.quickSources || {};</script>
<?php if($openModal): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const el = document.getElementById('missionCreateModal');
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
</script>
<?php endif; ?>
<?php }); ?>
