<?php $this->extend('layouts/main'); $this->section('content');
$title = $job["number"]." — ".$job["title"];
$sym = ["GBP"=>"£","EUR"=>"€","USD"=>"$"][$settings["regional"]["currency"]??"GBP"] ?? "£";
?>
<div class="d-flex justify-content-between align-items-start mb-3">
    <a href="/fieldly/public/index.php/jobs" class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i> Jobs</a>
    <div class="d-flex gap-2 flex-wrap">
        <?php if (in_array("edit_jobs", $permissions)): ?>
        <a href="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>/edit" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil me-1"></i> Edit</a>
        <form method="POST" action="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>/duplicate" class="d-inline"><?php echo csrf_field() ?><button type="submit" class="btn btn-sm btn-outline-secondary"><i class="bi bi-copy me-1"></i> Duplicate</button></form>
        <?php endif; ?>
        <?php if (in_array("complete_jobs", $permissions) && !($job["status"]["is_complete"]??0)): ?>
        <button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#completeModal"><i class="bi bi-check-lg me-1"></i> Complete</button>
        <?php endif; ?>
        <?php if (in_array("edit_invoices", $permissions)): ?>
        <a href="/fieldly/public/index.php/invoices/from-job/<?php echo $job["id"] ?>" class="btn btn-sm btn-outline-success"><i class="bi bi-receipt me-1"></i> Invoice</a>
        <?php endif; ?>
        <?php if (in_array("edit_jobs", $permissions)): ?>
        <form method="POST" action="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>/delete" data-confirm="Move to recycle bin?" class="d-inline"><?php echo csrf_field() ?><button type="submit" class="btn btn-sm btn-outline-danger"><i class="bi bi-trash3"></i></button></form>
        <?php endif; ?>
    </div>
</div>

<!-- Header Card -->
<div class="card mb-3">
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-8">
                <div class="d-flex gap-2 mb-2 flex-wrap">
                    <span class="badge" style="background:<?php echo esc($job["status"]["color"]??"#6b7280") ?>"><?php echo esc($job["status"]["name"]??"Unknown") ?></span>
                    <?php if ($job["type"]): ?><span class="badge bg-light text-dark"><?php echo esc($job["type"]["name"]) ?></span><?php endif; ?>
                    <span class="badge bg-light text-dark priority-<?php echo esc($job["priority"]) ?>"><?php echo ucfirst(esc($job["priority"])) ?> Priority</span>
                    <span class="badge bg-light text-dark"><?php echo esc($job["number"]) ?></span>
                </div>
                <h4 class="fw-bold mb-1"><?php echo esc($job["title"]) ?></h4>
                <?php if ($job["description"]): ?><p class="text-muted mb-0" style="font-size:14px"><?php echo esc($job["description"]) ?></p><?php endif; ?>
            </div>
            <div class="col-md-4">
                <div class="detail-row"><span class="detail-label">Customer</span><span class="detail-value"><a href="/fieldly/public/index.php/customers/<?php echo $job["customer"]["id"] ?>"><?php echo esc($job["customer"]["company_name"] ?: $job["customer"]["first_name"]." ".$job["customer"]["last_name"]) ?></a></span></div>
                <?php if ($job["scheduled_date"]): ?><div class="detail-row"><span class="detail-label">Scheduled</span><span class="detail-value"><?php echo date("d M Y", strtotime($job["scheduled_date"])) ?><?php if ($job["scheduled_time"]): ?> <?php echo date("H:i", strtotime($job["scheduled_time"])) ?><?php endif; ?></span></div><?php endif; ?>
                <?php if (!empty($job["assignees"])): ?>
                <div class="detail-row"><span class="detail-label">Assigned To</span><span class="detail-value"><?php foreach ($job["assignees"] as $a): ?><span class="badge me-1" style="background:<?php echo esc($a["color"]) ?>"><?php echo esc($a["first_name"]." ".$a["last_name"]) ?></span><?php endforeach; ?></span></div>
                <?php endif; ?>
                <?php if ($totalMins > 0): ?><div class="detail-row"><span class="detail-label">Time Logged</span><span class="detail-value"><?php echo floor($totalMins/60) ?>h <?php echo $totalMins%60 ?>m (<?php echo floor($billableMins/60) ?>h <?php echo $billableMins%60 ?>m billable)</span></div><?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Check In/Out -->
<?php
$openCI = db_connect()->table("check_ins")->where("company_id",session("company_id"))->where("user_id",session("user_id"))->where("job_id",$job["id"])->where("checked_out_at IS NULL",null,false)->get()->getRowArray();
?>
<?php if (!($job["status"]["is_complete"]??0)): ?>
<div class="card mb-3">
    <div class="card-body d-flex align-items-center gap-3">
        <div class="flex-grow-1">
            <?php if ($openCI): ?>
            <div class="text-success fw-semibold"><i class="bi bi-geo-alt-fill me-1"></i> Checked in since <?php echo date("H:i", strtotime($openCI["checked_in_at"])) ?></div>
            <?php else: ?>
            <div class="text-muted" style="font-size:14px">Not currently checked in</div>
            <?php endif; ?>
        </div>
        <?php if ($openCI): ?>
        <form method="POST" action="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>/checkout"><?php echo csrf_field() ?><button type="submit" class="btn btn-warning btn-sm"><i class="bi bi-geo me-1"></i> Check Out</button></form>
        <?php else: ?>
        <form method="POST" action="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>/checkin"><?php echo csrf_field() ?><button type="submit" class="btn btn-success btn-sm"><i class="bi bi-geo-fill me-1"></i> Check In</button></form>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- Tabs -->
<div class="fieldly-tabs">
    <?php foreach (["overview"=>"Overview","checklist"=>"Checklist (".count($job["checklists"]).")","time"=>"Time (".count($job["timeEntries"]).")","invoices"=>"Invoices (".count($job["invoices"]).")","visits"=>"Visits (".count($job["visits"]).")","notes"=>"Notes (".count($job["notes"]).")","files"=>"Files (".count($job["files"]).")"] as $t=>$label): ?>
    <a class="fieldly-tab <?php echo $tab===$t?"active":"" ?>" href="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>?tab=<?php echo $t ?>"><?php echo $label ?></a>
    <?php endforeach; ?>
</div>

<?php if ($tab==="overview"): ?>
<div class="row g-3">
    <?php if ($job["internal_notes"]): ?>
    <div class="col-12"><div class="card"><div class="card-header"><h6 class="mb-0"><i class="bi bi-lock-fill text-warning me-2"></i>Internal Notes</h6></div><div class="card-body" style="font-size:14px;white-space:pre-wrap"><?php echo esc($job["internal_notes"]) ?></div></div></div>
    <?php endif; ?>
    <?php if ($job["customer_notes"]): ?>
    <div class="col-12"><div class="card"><div class="card-header"><h6 class="mb-0">Customer Notes</h6></div><div class="card-body" style="font-size:14px;white-space:pre-wrap"><?php echo esc($job["customer_notes"]) ?></div></div></div>
    <?php endif; ?>
    <?php if (!empty($job["credits"])): ?>
    <div class="col-12"><div class="card"><div class="card-header"><h6 class="mb-0">Pre-payments / Credits</h6></div><div class="card-body p-0"><table class="table table-sm mb-0"><thead><tr><th>Date</th><th>Method</th><th>Ref</th><th>Amount</th><th>Applied</th></tr></thead><tbody><?php foreach ($job["credits"] as $cr): ?><tr><td style="font-size:13px"><?php echo date("d M Y",strtotime($cr["created_at"])) ?></td><td><?php echo ucfirst(str_replace("_"," ",$cr["method"])) ?></td><td><?php echo esc($cr["reference"]) ?></td><td class="fw-bold"><?php echo $sym.number_format((float)$cr["amount"],2) ?></td><td><?php echo $cr["applied"]?'<span class="badge bg-success">Applied</span>':'<span class="badge bg-warning text-dark">Pending</span>' ?></td></tr><?php endforeach; ?></tbody></table></div></div></div>
    <?php endif; ?>
</div>

<?php elseif ($tab==="checklist"): ?>
<div class="row">
    <div class="col-md-8">
        <?php foreach ($job["checklists"] as $item): ?>
        <div class="d-flex align-items-center gap-3 p-3 mb-2 rounded border <?php echo $item["completed"]?"bg-light text-muted":"bg-white" ?>">
            <form method="POST" action="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>/checklist/<?php echo $item["id"] ?>"><?php echo csrf_field() ?>
                <button type="submit" class="btn btn-<?php echo $item["completed"]?"success":"outline-secondary" ?> btn-sm btn-icon"><i class="bi bi-check"></i></button>
            </form>
            <span style="<?php echo $item["completed"]?"text-decoration:line-through;":"" ?>;font-size:14px"><?php echo esc($item["text"]) ?></span>
            <?php if ($item["completed"]): ?><span class="ms-auto text-muted small">Done</span><?php endif; ?>
        </div>
        <?php endforeach; ?>
        <?php if (empty($job["checklists"])): ?><p class="text-muted">No checklist items.</p><?php endif; ?>
    </div>
</div>

<?php elseif ($tab==="time"): ?>
<div class="row">
    <div class="col-md-8">
        <div class="card mb-3"><div class="card-body p-0"><table class="table table-sm mb-0"><thead><tr><th>Date</th><th>Engineer</th><th>Duration</th><th>Billable</th><th>Notes</th></tr></thead><tbody>
        <?php foreach ($job["timeEntries"] as $te): ?>
        <tr><td style="font-size:13px"><?php echo date("d M Y",strtotime($te["date"])) ?></td><td style="font-size:13px"><?php echo esc($te["first_name"]." ".$te["last_name"]) ?></td><td style="font-size:13px"><?php echo floor($te["duration_mins"]/60) ?>h <?php echo $te["duration_mins"]%60 ?>m</td><td><?php echo $te["billable"]?'<span class="badge bg-success">Yes</span>':'<span class="badge bg-secondary">No</span>' ?></td><td style="font-size:13px"><?php echo esc($te["notes"]) ?></td></tr>
        <?php endforeach; ?>
        <?php if (empty($job["timeEntries"])): ?><tr><td colspan="5" class="text-center text-muted py-3">No time entries</td></tr><?php endif; ?>
        </tbody></table></div></div>
    </div>
    <?php if (in_array("log_time", $permissions)): ?>
    <div class="col-md-4">
        <div class="card"><div class="card-header"><h6 class="mb-0">Log Time</h6></div><div class="card-body">
            <form method="POST" action="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>/time">
                <?php echo csrf_field() ?>
                <div class="mb-2"><label class="form-label">Date</label><input type="date" name="date" class="form-control form-control-sm" value="<?php echo date("Y-m-d") ?>"/></div>
                <div class="mb-2"><label class="form-label">Duration (mins)</label><input type="number" name="duration_mins" class="form-control form-control-sm" min="1" required/></div>
                <div class="mb-2"><label class="form-label">Hourly Rate</label><input type="number" name="rate" class="form-control form-control-sm" step="0.01" value="<?php echo $currentUser["hourly_rate"]??0 ?>"/></div>
                <div class="mb-2 form-check"><input type="checkbox" name="billable" class="form-check-input" id="billable" checked/><label class="form-check-label" for="billable">Billable</label></div>
                <div class="mb-2"><textarea name="notes" class="form-control form-control-sm" rows="2" placeholder="Notes..."></textarea></div>
                <button type="submit" class="btn btn-primary btn-sm w-100">Log Time</button>
            </form>
        </div></div>
    </div>
    <?php endif; ?>
</div>

<?php elseif ($tab==="invoices"): ?>
<div class="mb-2"><?php if (in_array("edit_invoices", $permissions)): ?><a href="/fieldly/public/index.php/invoices/from-job/<?php echo $job["id"] ?>" class="btn btn-sm btn-outline-success"><i class="bi bi-plus me-1"></i> Create Invoice</a><?php endif; ?></div>
<div class="card"><div class="card-body p-0"><table class="table mb-0"><thead><tr><th>Invoice</th><th>Status</th><th>Total</th><th>Balance</th><th></th></tr></thead><tbody>
<?php foreach ($job["invoices"] as $inv): ?><tr><td><a href="/fieldly/public/index.php/invoices/<?php echo $inv["id"] ?>"><?php echo esc($inv["number"]) ?></a></td><td><span class="badge bg-<?php echo ["paid"=>"success","overdue"=>"danger","draft"=>"secondary","sent"=>"primary","part_paid"=>"warning","void"=>"dark"][$inv["status"]]??"secondary" ?>"><?php echo ucfirst(str_replace("_"," ",$inv["status"])) ?></span></td><td><?php echo $sym.number_format((float)$inv["total"],2) ?></td><td><?php echo $sym.number_format((float)$inv["balance_due"],2) ?></td><td><a href="/fieldly/public/index.php/invoices/<?php echo $inv["id"] ?>" class="btn btn-sm btn-outline-secondary"><i class="bi bi-eye"></i></a></td></tr><?php endforeach; ?>
<?php if (empty($job["invoices"])): ?><tr><td colspan="5" class="text-center text-muted py-3">No invoices</td></tr><?php endif; ?>
</tbody></table></div></div>

<?php elseif ($tab==="notes"): ?>
<div class="row">
    <div class="col-md-8">
        <?php foreach ($job["notes"] as $n): ?><div class="note-item"><div class="note-text"><?php echo nl2br(esc($n["text"])) ?></div><div class="note-meta"><?php echo esc($n["first_name"]." ".$n["last_name"]) ?> · <?php echo date("d M Y H:i",strtotime($n["created_at"])) ?></div></div><?php endforeach; ?>
        <?php if (empty($job["notes"])): ?><p class="text-muted">No notes yet.</p><?php endif; ?>
    </div>
    <?php if (in_array("manage_notes", $permissions)): ?>
    <div class="col-md-4"><div class="card"><div class="card-header"><h6 class="mb-0">Add Note</h6></div><div class="card-body"><form method="POST" action="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>/note"><?php echo csrf_field() ?><textarea name="text" class="form-control mb-2" rows="4" required></textarea><button type="submit" class="btn btn-primary btn-sm w-100">Add Note</button></form></div></div></div>
    <?php endif; ?>
</div>

<?php elseif ($tab==="files"): ?>
<div class="row">
    <div class="col-md-8"><div class="card"><div class="card-body p-0"><table class="table mb-0"><thead><tr><th>File</th><th>Size</th><th>Uploaded</th></tr></thead><tbody><?php foreach ($job["files"] as $f): ?><tr><td><?php echo esc($f["original_name"]) ?></td><td style="font-size:13px"><?php echo round($f["file_size"]/1024,1) ?>KB</td><td style="font-size:13px"><?php echo date("d M Y",strtotime($f["created_at"])) ?></td></tr><?php endforeach; ?><?php if (empty($job["files"])): ?><tr><td colspan="3" class="text-center text-muted py-3">No files</td></tr><?php endif; ?></tbody></table></div></div></div>
    <?php if (in_array("manage_files", $permissions)): ?><div class="col-md-4"><div class="card"><div class="card-header"><h6 class="mb-0">Upload</h6></div><div class="card-body"><form method="POST" action="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>/file" enctype="multipart/form-data"><?php echo csrf_field() ?><input type="file" name="file" class="form-control mb-2" required/><button type="submit" class="btn btn-primary btn-sm w-100"><i class="bi bi-upload me-1"></i> Upload</button></form></div></div></div><?php endif; ?>
</div>

<?php elseif ($tab==="visits"): ?>
<div class="card"><div class="card-body p-0"><table class="table mb-0"><thead><tr><th>Title</th><th>Start</th><th>End</th><th>Status</th></tr></thead><tbody>
<?php foreach ($job["visits"] as $v): ?><tr><td><?php echo esc($v["title"]) ?></td><td style="font-size:13px"><?php echo date("d M Y H:i",strtotime($v["scheduled_start"])) ?></td><td style="font-size:13px"><?php echo $v["scheduled_end"] ? date("H:i",strtotime($v["scheduled_end"])) : "—" ?></td><td><span class="badge bg-secondary"><?php echo ucfirst($v["status"]) ?></span></td></tr><?php endforeach; ?>
<?php if (empty($job["visits"])): ?><tr><td colspan="4" class="text-center text-muted py-3">No visits scheduled</td></tr><?php endif; ?>
</tbody></table></div></div>
<?php endif; ?>

<!-- Complete Modal -->
<div class="modal fade" id="completeModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="POST" action="/fieldly/public/index.php/jobs/<?php echo $job["id"] ?>/complete">
                <?php echo csrf_field() ?>
                <div class="modal-header"><h5 class="modal-title">Complete Job</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <label class="form-label">Completion Note (optional)</label>
                    <textarea name="note" class="form-control" rows="4" placeholder="Any notes about the completed work..."></textarea>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-success">Mark Complete</button></div>
            </form>
        </div>
    </div>
</div>
<?php $this->endSection(); ?>