<?php
require_once __DIR__ . '/core/auth.php';
$user = require_login();
$pdo = pdo();
$reportId = (int) ($_GET['id'] ?? 0);
$agents = get_accessible_agents($pdo, $user);
$agentRecords = get_accessible_agent_records($pdo, $user);
$agentDirectory = [];
foreach ($agentRecords as $row) {
    $agentDirectory[$row['agent_name']] = [
        'agent_name' => $row['agent_name'],
        'rsm_name' => $row['rsm_name'] ?? '',
        'region' => $row['region'] ?? '',
        'sub_region' => $row['sub_region'] ?? '',
        'territory_name' => $row['territory_name'] ?? '',
        'dbaddres' => $row['dbaddres'] ?? '',
        'dbcontact' => $row['dbcontact'] ?? '',
        'stores_name' => $row['stores_name'] ?? '',
    ];
}

$bundle = [
    'report' => null,
    'db_profile' => [],
    'sales_snapshot' => [],
    'stock_status' => [],
    'issues' => [],
    'actions_db' => [],
    'actions_staff' => [],
    'follow_ups' => [],
    'general' => [],
    'progress' => [],
];

if ($reportId > 0) {
    require_report_access($pdo, $user, $reportId);
    $bundle = fetch_report_bundle($pdo, $reportId);
}

$report = $bundle['report'] ?? [];
$profile = $bundle['db_profile'] ?? [];
$general = $bundle['general'] ?? [];
$selectedAgent = $report['agent_name'] ?? '';
$selectedAgentDetails = $selectedAgent && isset($agentDirectory[$selectedAgent]) ? $agentDirectory[$selectedAgent] : null;
$progressMap = [];
foreach (($bundle['progress'] ?? []) as $progress) {
    $progressMap[(int) $progress['form_no']] = true;
}

$salesRows = [];
foreach (report_categories() as $category) {
    $salesRows[$category] = ['category_name' => $category, 'mtd_target' => '', 'mtd_achievement' => '', 'variance' => '', 'status_remarks' => ''];
}
foreach (($bundle['sales_snapshot'] ?? []) as $row) {
    $salesRows[$row['category_name']] = $row;
}

$stockRows = $bundle['stock_status'] ?: array_fill(0, 10, ['product_name' => '', 'stock_level' => '', 'system_stock' => '', 'variance' => '', 'variance_comment' => '']);
$issueRows = $bundle['issues'] ?: [['issue_type' => 'Sales', 'description' => '', 'severity' => 'N/A']];
$dbActionDefaults = ['Increase sales focus', 'Expedite stock replenishment', 'Improve outlet coverage'];
$staffActionDefaults = ['ASM', 'ASE', 'CSR'];
$dbActionMap = [];
foreach (($bundle['actions_db'] ?? []) as $row) { $dbActionMap[$row['action_name']] = $row['comments']; }
$staffActionMap = [];
foreach (($bundle['actions_staff'] ?? []) as $row) { $staffActionMap[$row['staff_role']] = $row['comments']; }
$followRows = $bundle['follow_ups'] ?: [
    ['action_name' => 'Replenish stock', 'responsible_person' => '', 'deadline_period' => '1 month'],
    ['action_name' => 'Monitor coverage', 'responsible_person' => '', 'deadline_period' => '3 months'],
];
$bootstrapPayload = [
    'reportId' => $reportId,
    'agentDirectory' => $agentDirectory,
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $reportId ? 'Edit Report' : 'New Report' ?> - <?= e(app_name()) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/app.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg bg-white border-bottom sticky-top">
    <div class="container-fluid px-3">
        <a class="navbar-brand fw-bold" href="dashboard.php"><?= e(app_name()) ?></a>
        <div class="d-flex gap-2">
            <a href="reports.php" class="btn btn-outline-secondary btn-sm">Reports</a>
            <a href="logout.php" class="btn btn-outline-danger btn-sm">Logout</a>
        </div>
    </div>
</nav>
<div class="container py-4" id="report-app" data-report-id="<?= (int) $reportId ?>">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4">
        <div>
            <h1 class="h3 mb-1"><?= $reportId ? 'Edit Field Report' : 'Create Field Report' ?></h1>
            <p class="text-muted mb-0">Save Form 01 first, then complete Forms 02-07 before finalizing Form 08.</p>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <?php for ($i = 1; $i <= 8; $i++): ?>
                <span class="badge <?= isset($progressMap[$i]) ? 'text-bg-success' : 'text-bg-secondary' ?>">Form <?= sprintf('%02d', $i) ?></span>
            <?php endfor; ?>
            <?php if ($reportId): ?><a href="report_view.php?id=<?= (int) $reportId ?>" class="btn btn-sm btn-outline-primary">View Summary</a><?php endif; ?>
        </div>
    </div>

    <div id="saveStatus" class="alert alert-info py-2 small">Start with Form 01. Final submission is locked until Forms 01-07 are saved.</div>

    <div class="accordion" id="reportAccordion">
        <div class="accordion-item mb-3 border-0 shadow-sm">
            <h2 class="accordion-header"><button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#form01">Form 01 - Visit Details</button></h2>
            <div id="form01" class="accordion-collapse collapse show" data-bs-parent="#reportAccordion">
                <div class="accordion-body">
                    <form id="form1" class="persist-local" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                        <input type="hidden" name="report_id" value="<?= (int) $reportId ?>">
                        <input type="hidden" name="start_lat" value="<?= e($report['start_lat'] ?? '') ?>">
                        <input type="hidden" name="start_lng" value="<?= e($report['start_lng'] ?? '') ?>">
                        <div class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">Date of Visit</label>
                                <input type="datetime-local" name="date_of_visit" class="form-control" value="<?= e(isset($report['date_of_visit']) ? date('Y-m-d\TH:i', strtotime($report['date_of_visit'])) : current_datetime_local()) ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">DB Name</label>
                                <input list="agentNames" name="agent_name" id="agent_name" class="form-control" value="<?= e($selectedAgent) ?>" required>
                                <datalist id="agentNames">
                                    <?php foreach ($agents as $agent): ?><option value="<?= e($agent) ?>"><?php endforeach; ?>
                                </datalist>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Accompanied By</label>
                                <input type="text" name="accompanied_by" class="form-control" value="<?= e($report['accompanied_by'] ?? '') ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Visited Type</label>
                                <select name="visited_type" class="form-select" required>
                                    <option value="">Select</option>
                                    <?php foreach (visit_types() as $type): ?>
                                        <option value="<?= e($type) ?>" <?= ($report['visited_type'] ?? '') === $type ? 'selected' : '' ?>><?= e($type) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="card bg-light border-0 mt-3" id="agentDetailsCard">
                            <div class="card-body py-3 small">
                                <div class="fw-semibold mb-2">Selected DB information</div>
                                <div class="row g-2">
                                    <div class="col-md-3"><span class="text-muted">Contact:</span> <span id="agentContactText"><?= e($selectedAgentDetails['dbcontact'] ?? '-') ?></span></div>
                                    <div class="col-md-3"><span class="text-muted">Territory:</span> <span id="agentTerritoryText"><?= e($selectedAgentDetails['territory_name'] ?? '-') ?></span></div>
                                    <div class="col-md-3"><span class="text-muted">Region:</span> <span id="agentRegionText"><?= e($selectedAgentDetails['region'] ?? '-') ?></span></div>
                                    <div class="col-md-3"><span class="text-muted">Address:</span> <span id="agentAddressText"><?= e($selectedAgentDetails['dbaddres'] ?? '-') ?></span></div>
                                </div>
                                <div class="text-muted mt-2">Choosing a DB can auto-fill contact and coverage hints in Form 02.</div>
                            </div>
                        </div>
                        <div class="mt-3 d-flex gap-2 flex-wrap">
                            <button type="button" class="btn btn-primary save-section" data-form="form1" data-action="save_form1" data-capture-location="start">Save Form 01 & Start Report</button>
                            <span class="small text-muted align-self-center">On first save, start time and GPS are captured.</span>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="accordion-item mb-3 border-0 shadow-sm">
            <h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#form02">Form 02 - DB Profile</button></h2>
            <div id="form02" class="accordion-collapse collapse" data-bs-parent="#reportAccordion">
                <div class="accordion-body">
                    <form id="form2" class="persist-local" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"><input type="hidden" name="report_id" value="<?= (int) $reportId ?>">
                        <input type="hidden" name="webcam_route_map" id="webcam_route_map" value="">
                        <input type="hidden" name="territory_route_map_remove" id="territory_route_map_remove" value="0">
                        <div class="row g-3">
                            <div class="col-md-4"><label class="form-label">DB Owner / Contact Number</label><input name="owner_contact" id="owner_contact" class="form-control" value="<?= e($profile['owner_contact'] ?? '') ?>"></div>
                            <div class="col-md-4"><label class="form-label">Coverage Area</label><input name="coverage_area" id="coverage_area" class="form-control" value="<?= e($profile['coverage_area'] ?? '') ?>"></div>
                            <div class="col-md-4"><label class="form-label">Route Strength</label><input name="route_strength" class="form-control" value="<?= e($profile['route_strength'] ?? '') ?>"></div>
                            <div class="col-md-4"><label class="form-label">Vehicle Availability</label><input name="vehicle_availability" class="form-control" value="<?= e($profile['vehicle_availability'] ?? '') ?>"></div>
                            <div class="col-md-4"><label class="form-label">Log Book Update</label><select name="log_book_updated" class="form-select"><?php foreach (yes_no_options() as $option): ?><option value="<?= e($option) ?>" <?= ($profile['log_book_updated'] ?? 'No') === $option ? 'selected' : '' ?>><?= e($option) ?></option><?php endforeach; ?></select></div>
                            <div class="col-md-4"><label class="form-label">Territory Route Map</label><select name="territory_route_map" id="territory_route_map" class="form-select"><?php foreach (yes_no_options() as $option): ?><option value="<?= e($option) ?>" <?= ($profile['territory_route_map'] ?? 'No') === $option ? 'selected' : '' ?>><?= e($option) ?></option><?php endforeach; ?></select></div>
                            <div class="col-12 route-map-upload <?= (($profile['territory_route_map'] ?? 'No') === 'Yes') ? '' : 'd-none' ?>">
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Upload Route Map Image</label>
                                        <input type="file" name="territory_route_map_file" accept="image/*" capture="environment" class="form-control">
                                        <?php if (!empty($profile['territory_route_map_file'])): ?><div class="form-text"><a href="<?= e($profile['territory_route_map_file']) ?>" target="_blank">Current image</a></div><?php endif; ?>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label d-block">Laptop Camera Capture</label>
                                        <button type="button" class="btn btn-outline-secondary btn-sm mb-2" id="startWebcam">Open Camera</button>
                                        <button type="button" class="btn btn-outline-primary btn-sm mb-2" id="captureWebcam">Capture</button>
                                        <div class="webcam-box"><video id="webcamVideo" autoplay playsinline></video></div>
                                        <img id="webcamPreview" class="img-fluid rounded border mt-2 d-none" src="" alt="Route map preview">
                                        <?php if (!empty($profile['territory_route_map_file'])): ?><img id="existingRouteMapPreview" class="img-fluid rounded border mt-2" src="<?= e($profile['territory_route_map_file']) ?>" alt="Existing route map"><?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4"><label class="form-label">Route Plan</label><select name="route_plan" class="form-select"><?php foreach (yes_no_options() as $option): ?><option value="<?= e($option) ?>" <?= ($profile['route_plan'] ?? 'No') === $option ? 'selected' : '' ?>><?= e($option) ?></option><?php endforeach; ?></select></div>
                            <div class="col-md-4"><label class="form-label">No of Credit Bills</label><input type="number" step="1" name="no_credit_bills" class="form-control" value="<?= e($profile['no_credit_bills'] ?? '0') ?>"></div>
                            <div class="col-md-4"><label class="form-label">Credit Bill Total Amount</label><input type="number" step="0.01" name="credit_bill_total" class="form-control" value="<?= e($profile['credit_bill_total'] ?? '0') ?>"></div>
                            <div class="col-md-4"><label class="form-label">No of Cheques</label><input type="number" step="1" name="no_cheques" class="form-control" value="<?= e($profile['no_cheques'] ?? '0') ?>"></div>
                            <div class="col-md-4"><label class="form-label">Cheque Total Amount</label><input type="number" step="0.01" name="cheque_total" class="form-control" value="<?= e($profile['cheque_total'] ?? '0') ?>"></div>
                            <div class="col-md-4"><label class="form-label">Cash + Bank Total Amount</label><input type="number" step="0.01" name="cash_bank_total" class="form-control" value="<?= e($profile['cash_bank_total'] ?? '0') ?>"></div>
                            <div class="col-md-3"><label class="form-label">Progress Sheet Update</label><select name="progress_sheet_updated" class="form-select"><?php foreach (yes_no_options() as $option): ?><option value="<?= e($option) ?>" <?= ($profile['progress_sheet_updated'] ?? 'No') === $option ? 'selected' : '' ?>><?= e($option) ?></option><?php endforeach; ?></select></div>
                            <div class="col-md-9"><label class="form-label">Progress Sheet Comment</label><input name="progress_sheet_comment" class="form-control" value="<?= e($profile['progress_sheet_comment'] ?? '') ?>"></div>
                            <div class="col-md-3"><label class="form-label">SKU Sales Update</label><select name="sku_sales_update" class="form-select"><?php foreach (['Low', 'Moderate', 'High'] as $option): ?><option value="<?= e($option) ?>" <?= ($profile['sku_sales_update'] ?? 'Low') === $option ? 'selected' : '' ?>><?= e($option) ?></option><?php endforeach; ?></select></div>
                            <div class="col-md-9"><label class="form-label">SKU Sales Comment</label><input name="sku_sales_comment" class="form-control" value="<?= e($profile['sku_sales_comment'] ?? '') ?>"></div>
                            <div class="col-md-3"><label class="form-label">Store Length</label><input type="number" step="0.01" name="store_length" class="form-control" value="<?= e($profile['store_length'] ?? '') ?>"></div>
                            <div class="col-md-3"><label class="form-label">Store Width</label><input type="number" step="0.01" name="store_width" class="form-control" value="<?= e($profile['store_width'] ?? '') ?>"></div>
                            <div class="col-md-3"><label class="form-label">Store Table Count</label><input type="number" step="1" name="store_table_count" class="form-control" value="<?= e($profile['store_table_count'] ?? '0') ?>"></div>
                            <div class="col-md-3"><label class="form-label">Store Chair Count</label><input type="number" step="1" name="store_chair_count" class="form-control" value="<?= e($profile['store_chair_count'] ?? '0') ?>"></div>
                            <div class="col-md-6"><label class="form-label">Store Condition</label><textarea name="store_condition" class="form-control" rows="2"><?= e($profile['store_condition'] ?? '') ?></textarea></div>
                            <div class="col-md-6"><label class="form-label">Market Return Condition</label><textarea name="market_return_condition" class="form-control" rows="2"><?= e($profile['market_return_condition'] ?? '') ?></textarea></div>
                            <div class="col-12"><label class="form-label">Store Comments</label><textarea name="store_comments" class="form-control" rows="3"><?= e($profile['store_comments'] ?? '') ?></textarea></div>
                        </div>
                        <div class="mt-3"><button type="button" class="btn btn-primary save-section" data-form="form2" data-action="save_form2">Save Form 02</button></div>
                    </form>
                </div>
            </div>
        </div>

        <div class="accordion-item mb-3 border-0 shadow-sm">
            <h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#form03">Form 03 - Sales Snapshot</button></h2>
            <div id="form03" class="accordion-collapse collapse" data-bs-parent="#reportAccordion">
                <div class="accordion-body">
                    <form id="form3" class="persist-local">
                        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"><input type="hidden" name="report_id" value="<?= (int) $reportId ?>">
                        <div class="table-responsive">
                            <table class="table align-middle" id="salesSnapshotTable">
                                <thead class="table-light"><tr><th>Category</th><th>MTD Target</th><th>MTD Achievement</th><th>Variance</th><th>Status Remarks</th></tr></thead>
                                <tbody>
                                <?php foreach ($salesRows as $row): ?>
                                    <tr>
                                        <td><input type="text" name="category_name[]" class="form-control form-control-sm" value="<?= e($row['category_name']) ?>" readonly></td>
                                        <td><input type="number" step="0.01" name="mtd_target[]" class="form-control form-control-sm sales-target" value="<?= e($row['mtd_target']) ?>"></td>
                                        <td><input type="number" step="0.01" name="mtd_achievement[]" class="form-control form-control-sm sales-achievement" value="<?= e($row['mtd_achievement']) ?>"></td>
                                        <td><input type="number" step="0.01" name="variance[]" class="form-control form-control-sm sales-variance" value="<?= e($row['variance']) ?>" readonly></td>
                                        <td><input type="text" name="status_remarks[]" class="form-control form-control-sm sales-status" value="<?= e($row['status_remarks']) ?>" readonly></td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <button type="button" class="btn btn-primary save-section" data-form="form3" data-action="save_form3">Save Form 03</button>
                    </form>
                </div>
            </div>
        </div>

        <div class="accordion-item mb-3 border-0 shadow-sm">
            <h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#form04">Form 04 - Stock Status</button></h2>
            <div id="form04" class="accordion-collapse collapse" data-bs-parent="#reportAccordion">
                <div class="accordion-body">
                    <form id="form4" class="persist-local">
                        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"><input type="hidden" name="report_id" value="<?= (int) $reportId ?>">
                        <div class="table-responsive">
                            <table class="table align-middle" id="stockStatusTable">
                                <thead class="table-light"><tr><th>Product Name</th><th>Stock Level</th><th>System Stock</th><th>Variance</th><th>Variance Comment</th><th></th></tr></thead>
                                <tbody>
                                <?php foreach ($stockRows as $row): ?>
                                    <tr>
                                        <td><input name="product_name[]" class="form-control form-control-sm" value="<?= e($row['product_name']) ?>"></td>
                                        <td><input type="number" step="1" name="stock_level[]" class="form-control form-control-sm stock-level" value="<?= e($row['stock_level']) ?>"></td>
                                        <td><input type="number" step="1" name="system_stock[]" class="form-control form-control-sm system-stock" value="<?= e($row['system_stock']) ?>"></td>
                                        <td><input type="number" step="1" name="stock_variance[]" class="form-control form-control-sm stock-variance" value="<?= e($row['variance']) ?>" readonly></td>
                                        <td><input name="variance_comment[]" class="form-control form-control-sm" value="<?= e($row['variance_comment']) ?>"></td>
                                        <td><button type="button" class="btn btn-sm btn-outline-danger remove-row">×</button></td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="d-flex gap-2 flex-wrap">
                            <button type="button" class="btn btn-outline-secondary" id="addStockRow">+ Add Product</button>
                            <button type="button" class="btn btn-primary save-section" data-form="form4" data-action="save_form4">Save Form 04</button>
                        </div>
                        <div class="small text-muted mt-2">At least 10 product rows are required before saving.</div>
                    </form>
                </div>
            </div>
        </div>

        <div class="accordion-item mb-3 border-0 shadow-sm">
            <h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#form05">Form 05 - Issues Identified</button></h2>
            <div id="form05" class="accordion-collapse collapse" data-bs-parent="#reportAccordion">
                <div class="accordion-body">
                    <form id="form5" class="persist-local">
                        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"><input type="hidden" name="report_id" value="<?= (int) $reportId ?>">
                        <div class="table-responsive">
                            <table class="table align-middle" id="issuesTable">
                                <thead class="table-light"><tr><th>Issue Type</th><th>Description</th><th>Severity</th><th></th></tr></thead>
                                <tbody>
                                <?php foreach ($issueRows as $row): ?>
                                    <tr>
                                        <td><select name="issue_type[]" class="form-select form-select-sm"><?php foreach (issue_types() as $type): ?><option value="<?= e($type) ?>" <?= $row['issue_type'] === $type ? 'selected' : '' ?>><?= e($type) ?></option><?php endforeach; ?></select></td>
                                        <td><input name="issue_description[]" class="form-control form-control-sm" value="<?= e($row['description']) ?>"></td>
                                        <td><select name="severity[]" class="form-select form-select-sm"><?php foreach (severity_levels() as $level): ?><option value="<?= e($level) ?>" <?= $row['severity'] === $level ? 'selected' : '' ?>><?= e($level) ?></option><?php endforeach; ?></select></td>
                                        <td><button type="button" class="btn btn-sm btn-outline-danger remove-row">×</button></td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="d-flex gap-2 flex-wrap">
                            <button type="button" class="btn btn-outline-secondary" id="addIssueRow">+ Add Issue</button>
                            <button type="button" class="btn btn-primary save-section" data-form="form5" data-action="save_form5">Save Form 05</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="accordion-item mb-3 border-0 shadow-sm">
            <h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#form06">Form 06 - Actions Agreed</button></h2>
            <div id="form06" class="accordion-collapse collapse" data-bs-parent="#reportAccordion">
                <div class="accordion-body">
                    <form id="form6" class="persist-local">
                        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"><input type="hidden" name="report_id" value="<?= (int) $reportId ?>">
                        <div class="row g-4">
                            <div class="col-12 col-lg-6">
                                <h3 class="h6">Action agreed with DB</h3>
                                <?php foreach ($dbActionDefaults as $action): ?>
                                    <div class="mb-3">
                                        <label class="form-label fw-semibold"><?= e($action) ?></label>
                                        <input type="hidden" name="db_action_name[]" value="<?= e($action) ?>">
                                        <textarea name="db_action_comment[]" class="form-control" rows="2"><?= e($dbActionMap[$action] ?? '') ?></textarea>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="col-12 col-lg-6">
                                <h3 class="h6">Action agreed with Staff</h3>
                                <?php foreach ($staffActionDefaults as $staff): ?>
                                    <div class="mb-3">
                                        <label class="form-label fw-semibold"><?= e($staff) ?></label>
                                        <input type="hidden" name="staff_role[]" value="<?= e($staff) ?>">
                                        <textarea name="staff_comment[]" class="form-control" rows="2"><?= e($staffActionMap[$staff] ?? '') ?></textarea>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <button type="button" class="btn btn-primary save-section" data-form="form6" data-action="save_form6">Save Form 06</button>
                    </form>
                </div>
            </div>
        </div>

        <div class="accordion-item mb-3 border-0 shadow-sm">
            <h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#form07">Form 07 - Follow Up</button></h2>
            <div id="form07" class="accordion-collapse collapse" data-bs-parent="#reportAccordion">
                <div class="accordion-body">
                    <form id="form7" class="persist-local">
                        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"><input type="hidden" name="report_id" value="<?= (int) $reportId ?>">
                        <div class="table-responsive">
                            <table class="table align-middle" id="followTable">
                                <thead class="table-light"><tr><th>Action</th><th>Responsible</th><th>Deadline</th><th></th></tr></thead>
                                <tbody>
                                <?php foreach ($followRows as $row): ?>
                                    <tr>
                                        <td><input name="follow_action[]" class="form-control form-control-sm" value="<?= e($row['action_name']) ?>"></td>
                                        <td><input name="follow_responsible[]" class="form-control form-control-sm" value="<?= e($row['responsible_person']) ?>"></td>
                                        <td><select name="follow_deadline[]" class="form-select form-select-sm"><?php foreach (follow_up_periods() as $period): ?><option value="<?= e($period) ?>" <?= $row['deadline_period'] === $period ? 'selected' : '' ?>><?= e($period) ?></option><?php endforeach; ?></select></td>
                                        <td><button type="button" class="btn btn-sm btn-outline-danger remove-row">×</button></td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="d-flex gap-2 flex-wrap">
                            <button type="button" class="btn btn-outline-secondary" id="addFollowRow">+ Add Follow Up</button>
                            <button type="button" class="btn btn-primary save-section" data-form="form7" data-action="save_form7">Save Form 07</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="accordion-item mb-3 border-0 shadow-sm">
            <h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#form08">Form 08 - General Remark & Signatures</button></h2>
            <div id="form08" class="accordion-collapse collapse" data-bs-parent="#reportAccordion">
                <div class="accordion-body">
                    <form id="form8" class="persist-local">
                        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"><input type="hidden" name="report_id" value="<?= (int) $reportId ?>">
                        <input type="hidden" name="end_lat" value="<?= e($report['end_lat'] ?? '') ?>"><input type="hidden" name="end_lng" value="<?= e($report['end_lng'] ?? '') ?>">
                        <input type="hidden" name="prepared_signature_remove" id="prepared_signature_remove" value="0">
                        <input type="hidden" name="distributor_signature_remove" id="distributor_signature_remove" value="0">
                        <input type="hidden" name="employee_signature_remove" id="employee_signature_remove" value="0">
                        <div class="mb-3"><label class="form-label">General Remark</label><textarea name="remark" class="form-control" rows="4"><?= e($general['remark'] ?? '') ?></textarea></div>
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Prepared by Signature</label>
                                <canvas class="signature-pad" id="prepared_signature_canvas"></canvas>
                                <input type="hidden" name="prepared_signature_data" id="prepared_signature_data">
                                <?php if (!empty($general['prepared_by_signature'])): ?><img src="<?= e($general['prepared_by_signature']) ?>" id="prepared_signature_existing" class="img-fluid rounded border mt-2" alt="Prepared signature"><?php endif; ?>
                                <button type="button" class="btn btn-sm btn-outline-secondary mt-2 clear-signature" data-target="prepared_signature_canvas">Clear</button>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Distributor Signature</label>
                                <canvas class="signature-pad" id="distributor_signature_canvas"></canvas>
                                <input type="hidden" name="distributor_signature_data" id="distributor_signature_data">
                                <?php if (!empty($general['distributor_signature'])): ?><img src="<?= e($general['distributor_signature']) ?>" id="distributor_signature_existing" class="img-fluid rounded border mt-2" alt="Distributor signature"><?php endif; ?>
                                <button type="button" class="btn btn-sm btn-outline-secondary mt-2 clear-signature" data-target="distributor_signature_canvas">Clear</button>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Employee Signature</label>
                                <canvas class="signature-pad" id="employee_signature_canvas"></canvas>
                                <input type="hidden" name="employee_signature_data" id="employee_signature_data">
                                <?php if (!empty($general['employee_signature'])): ?><img src="<?= e($general['employee_signature']) ?>" id="employee_signature_existing" class="img-fluid rounded border mt-2" alt="Employee signature"><?php endif; ?>
                                <button type="button" class="btn btn-sm btn-outline-secondary mt-2 clear-signature" data-target="employee_signature_canvas">Clear</button>
                            </div>
                        </div>
                        <div class="mt-3 d-flex gap-2 flex-wrap">
                            <button type="button" class="btn btn-success save-section" data-form="form8" data-action="save_form8" data-capture-location="end">Finalize & Save Form 08</button>
                            <?php if ($reportId): ?><a href="report_view.php?id=<?= (int) $reportId ?>" class="btn btn-outline-primary">Open Detailed View</a><?php endif; ?>
                            <span class="small text-muted align-self-center">Final save captures end GPS and keeps the first completion timestamp stable.</span>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
window.reportBootstrap = <?= json_encode($bootstrapPayload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/app.js"></script>
</body>
</html>
