<?php
require_once __DIR__ . "/../../config/config.php";
require_once __DIR__ . "/../../includes/functions.php";
startSession(); requireLogin();
$db = Database::getInstance();
$page = "On Duty";
$user = currentUser();
$empId = $user["emp_id"];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    verifyCsrf();
    $action = $_POST["action"] ?? "";

    if ($action === "apply") {
        $from      = post("from_date");
        $to        = post("to_date");
        $purpose   = post("purpose");
        $location  = post("location");
        $reason    = post("reason");
        $isFullDay = post("day_type") !== "partial";
        $fromTime  = $isFullDay ? null : post("from_time");
        $toTime    = $isFullDay ? null : post("to_time");
        $days      = max(1, (strtotime($to) - strtotime($from)) / 86400 + 1);

        if (!$from || !$to || !$purpose) {
            setFlash("error", "From date, to date and purpose are required.");
        } elseif (strtotime($to) < strtotime($from)) {
            setFlash("error", "To date cannot be before from date.");
        } elseif (!$isFullDay && $from !== $to) {
            setFlash("error", "A part-day On Duty request must be for a single date. Use Full Day for a date range.");
        } elseif (!$isFullDay && (!$fromTime || !$toTime)) {
            setFlash("error", "Please enter both the start and end time for a part-day request.");
        } elseif (!$isFullDay && strtotime($toTime) <= strtotime($fromTime)) {
            setFlash("error", "End time must be after start time.");
        } else {
            // Prevent overlapping active on-duty requests, same as leave.
            $overlap = $db->fetchValue(
                "SELECT COUNT(*) FROM on_duty_requests WHERE employee_id=? AND status NOT IN ('rejected','cancelled')
                 AND NOT (to_date < ? OR from_date > ?)",
                [$empId, $from, $to]
            );
            if ($overlap > 0) {
                setFlash("error", "You already have an On Duty request for the selected dates.");
            } else {
                $id = $db->insertRow("on_duty_requests", [
                    "employee_id" => $empId,
                    "from_date"   => $from,
                    "to_date"     => $to,
                    "is_full_day" => $isFullDay ? 1 : 0,
                    "from_time"   => $fromTime,
                    "to_time"     => $toTime,
                    "days"        => $days,
                    "purpose"     => $purpose,
                    "location"    => $location,
                    "reason"      => $reason,
                    "status"      => "pending",
                ]);
                $when = $isFullDay ? "$from to $to" : "$from, $fromTime–$toTime";
                notifyReportingHead($db, $empId, "New On Duty Request",
                    "{$user['first_name']} {$user['last_name']} requested On Duty ($when).",
                    "on_duty", $id);
                setFlash("success", $isFullDay ? "On Duty request submitted for $days day(s)." : "On Duty request submitted for $fromTime–$toTime on " . fmtDate($from) . ".");
            }
        }
    } elseif ($action === "cancel") {
        $db->execute("UPDATE on_duty_requests SET status='cancelled' WHERE id=? AND employee_id=? AND status='pending'",
            [postInt("id"), $empId]);
        setFlash("success", "On Duty request cancelled.");
    } elseif ($action === "approve" || $action === "reject") {
        requireRole('superadmin','admin','hr','manager','supervisor','hod','management');
        $orgCompanies = orgCompanyIds($db);
        $req = $db->fetchOne(
            "SELECT od.* FROM on_duty_requests od JOIN employees e ON e.id=od.employee_id WHERE od.id=? AND e.company_id IN (" . implode(',', array_fill(0, count($orgCompanies), '?')) . ")",
            array_merge([postInt("id")], $orgCompanies)
        );
        if (!$req) {
            setFlash("error", "Request not found.");
        } elseif ($req["status"] !== "pending") {
            setFlash("error", "Request already processed.");
        } else {
            $status  = $action === "approve" ? "approved" : "rejected";
            $remarks = post("reason") ?: null;
            $db->execute("UPDATE on_duty_requests SET status=?, approved_by=?, approved_at=NOW(), remarks=? WHERE id=?",
                [$status, $user["id"], $remarks, $req["id"]]);

            // On approval, mark each day of the range as 'OD' in the muster
            // (attendance) table — this is the whole point of On Duty: the
            // employee is away on official work but should not show as absent.
            // If they already have a real check-in/out for that day (e.g. they
            // signed in at office in the morning before heading out on duty),
            // that punch time is preserved — only the status changes, never
            // the actual times they clocked. Only a day with no punch at all
            // gets the on-duty from_time/to_time filled in, purely so reports
            // have something to show for a fully off-site day.
            if ($status === "approved") {
                $cursor = strtotime($req["from_date"]);
                $end    = strtotime($req["to_date"]);
                while ($cursor <= $end) {
                    $d = date("Y-m-d", $cursor);
                    $existing = $db->fetchOne("SELECT id, in_time, out_time FROM muster WHERE employee_id=? AND muster_date=?", [$req["employee_id"], $d]);
                    if ($existing) {
                        $set = ["status" => "OD"];
                        if (!$existing["in_time"] && $req["from_time"])  $set["in_time"]  = $req["from_time"];
                        if (!$existing["out_time"] && $req["to_time"])   $set["out_time"] = $req["to_time"];
                        $db->updateRow("muster", $set, $existing["id"]);
                    } else {
                        $db->insertRow("muster", [
                            "employee_id" => $req["employee_id"],
                            "muster_date" => $d,
                            "status"      => "OD",
                            "in_time"     => $req["from_time"],
                            "out_time"    => $req["to_time"],
                        ]);
                    }
                    $cursor = strtotime("+1 day", $cursor);
                }
            }

            notify($db, $req["employee_id"], "On Duty Request " . ucfirst($status),
                "Your On Duty request ({$req['from_date']} to {$req['to_date']}) was $status." . ($remarks ? " Remarks: $remarks" : ""),
                "on_duty", $req["id"]);
            setFlash("success", "On Duty request $status.");
        }
    }
    header("Location: " . BASE_URL . "/modules/attendance/onduty.php"); exit;
}

[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
$allReqs = $db->fetchAll(
    "SELECT od.*, CONCAT(e.first_name,' ',e.last_name) AS emp_name, e.employee_id AS emp_code
       FROM on_duty_requests od JOIN employees e ON e.id=od.employee_id
      WHERE $orgClause ORDER BY od.created_at DESC LIMIT 50",
    $orgParams
);
$myReqs = $empId ? array_filter($allReqs, fn($r) => $r["employee_id"] == $empId) : [];

include __DIR__ . "/../../includes/header.php";
?>
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-briefcase me-2"></i>Apply for On Duty</div>
      <p class="text-muted small mb-3">Use this when you're away from office for official work — a client visit, site inspection, or off-site meeting — so your attendance shows On Duty instead of Absent.</p>
      <form method="POST" id="odForm">
        <?=csrfField()?><input type="hidden" name="action" value="apply">

        <div class="mb-2">
          <label class="pc-label">Duration</label>
          <div class="btn-group w-100" role="group">
            <input type="radio" class="btn-check" name="day_type" id="odFull" value="full" checked>
            <label class="btn btn-outline-pc btn-sm" for="odFull">Full Day(s)</label>
            <input type="radio" class="btn-check" name="day_type" id="odPart" value="partial">
            <label class="btn btn-outline-pc btn-sm" for="odPart">Part of a Day</label>
          </div>
        </div>

        <div class="row g-2 mb-2">
          <div class="col"><label class="pc-label">From Date</label><input type="date" name="from_date" id="odFromDate" class="form-control form-control-sm" required></div>
          <div class="col" id="odToDateWrap"><label class="pc-label">To Date</label><input type="date" name="to_date" id="odToDate" class="form-control form-control-sm" required></div>
        </div>

        <div class="row g-2 mb-2 d-none" id="odTimeRow">
          <div class="col"><label class="pc-label">Start Time</label><input type="time" name="from_time" class="form-control form-control-sm"></div>
          <div class="col"><label class="pc-label">End Time</label><input type="time" name="to_time" class="form-control form-control-sm"></div>
        </div>
        <p class="text-muted small d-none" id="odPartHint" style="margin-top:-4px">e.g. signed in at office in the morning, then out on duty from 1:00 PM – 5:00 PM the same day.</p>

        <div class="mb-2"><label class="pc-label">Purpose <span class="text-danger">*</span></label>
          <input type="text" name="purpose" class="form-control form-control-sm" placeholder="e.g. Client site visit" required></div>
        <div class="mb-2"><label class="pc-label">Location</label>
          <input type="text" name="location" class="form-control form-control-sm" placeholder="e.g. Chennai branch office"></div>
        <div class="mb-3"><label class="pc-label">Reason / Notes</label>
          <textarea name="reason" class="form-control form-control-sm" rows="2"></textarea></div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-send me-1"></i>Submit Request</button>
      </form>
    </div>
  </div>
  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-list me-2"></i>All On Duty Requests</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Employee</th><th>From</th><th>To</th><th>Duration</th><th>Purpose</th><th>Location</th><th>Status</th><th>Action</th></tr></thead>
          <tbody>
          <?php foreach ($allReqs as $r): ?>
          <tr>
            <td><div class="fw-semibold"><?=clean($r["emp_name"])?></div><small class="text-muted"><?=clean($r["emp_code"])?></small></td>
            <td><?=fmtDate($r["from_date"])?></td>
            <td><?=fmtDate($r["to_date"])?></td>
            <td>
              <?php if (!$r["is_full_day"]): ?>
                <span class="fw-bold"><?=date("g:i A", strtotime($r["from_time"]))?> – <?=date("g:i A", strtotime($r["to_time"]))?></span>
                <div class="text-muted" style="font-size:11px">Part Day</div>
              <?php else: ?>
                <span class="fw-bold"><?=$r["days"]?> day<?=$r["days"]>1?"s":""?></span>
                <div class="text-muted" style="font-size:11px">Full Day</div>
              <?php endif; ?>
            </td>
            <td><?=clean($r["purpose"])?></td>
            <td><?=clean($r["location"] ?: "—")?></td>
            <td><?=statusBadge($r["status"])?></td>
            <td>
              <?php if ($r["status"] === "pending"): ?>
              <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="approve"><input type="hidden" name="id" value="<?=$r["id"]?>"><button class="btn btn-xs btn-success py-0 px-1">Approve</button></form>
              <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="reject"><input type="hidden" name="id" value="<?=$r["id"]?>"><input type="hidden" name="reason" value="Rejected by HR"><button class="btn btn-xs btn-danger py-0 px-1">Reject</button></form>
              <?php if ($r["employee_id"] == $empId): ?>
              <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="cancel"><input type="hidden" name="id" value="<?=$r["id"]?>"><button class="btn btn-xs btn-outline-secondary py-0 px-1">Cancel</button></form>
              <?php endif; ?>
              <?php else: ?>—<?php endif; ?>
            </td>
          </tr>
          <?php endforeach; if (!$allReqs): ?><tr><td colspan="8" class="text-center text-muted py-3">No On Duty requests</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<script>
(function(){
  const full = document.getElementById('odFull');
  const part = document.getElementById('odPart');
  const timeRow = document.getElementById('odTimeRow');
  const partHint = document.getElementById('odPartHint');
  const toDateWrap = document.getElementById('odToDateWrap');
  const fromDate = document.getElementById('odFromDate');
  const toDate = document.getElementById('odToDate');

  function sync() {
    const isPartial = part.checked;
    timeRow.classList.toggle('d-none', !isPartial);
    partHint.classList.toggle('d-none', !isPartial);
    toDateWrap.classList.toggle('d-none', isPartial);
    if (isPartial) toDate.value = fromDate.value;
  }
  full.addEventListener('change', sync);
  part.addEventListener('change', sync);
  fromDate.addEventListener('change', function(){ if (part.checked) toDate.value = fromDate.value; });
})();
</script>
<?php include __DIR__ . "/../../includes/footer.php"; ?>
