<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

$config = require __DIR__ . '/../../config/config.php';

auth_start_session();
auth_require_role(['customer']);

header('Location: ' . Constants::APP_ROOT . '/customer/my_services.php');
exit;

$user = auth_user();
$title = 'Service Reports';

$customerId = (int)($user['user_id'] ?? 0);

$q = trim((string)($_GET['q'] ?? ''));
$taskId = (int)($_GET['task_id'] ?? 0);

$rows = [];
$report = null;
$images = [];
$checklist = null;
$error = '';

$toPublic = function (string $p): string {
    $p = trim($p);
    if ($p === '') {
        return '';
    }
    if (preg_match('~^https?://~i', $p)) {
        return $p;
    }
    if (str_starts_with($p, Constants::ASSET_ROOT . '/')) {
        return $p;
    }
    if (str_starts_with($p, Constants::APP_ROOT . '/')) {
        return $p;
    }
    if (str_starts_with($p, '/uploads/')) {
        return Constants::APP_ROOT . $p;
    }
    if (str_starts_with($p, 'uploads/')) {
        return Constants::APP_ROOT . '/' . $p;
    }
    return $p;
};

$imageDetailLabel = function (string $p) use ($taskId): string {
    $p = trim($p);
    if ($p === '') {
        return '';
    }
    $norm = str_replace('\\', '/', $p);
    if (preg_match('~/uploads/tasks/(\d+)/(.*)$~', $norm, $m)) {
        $tail = (string)($m[2] ?? '');
        if (preg_match('~/(box_[^/]+)/~', '/' . $tail, $mm)) {
            $box = (string)($mm[1] ?? '');
            $box = substr($box, 4);
            $box = str_replace('_', ' ', $box);
            return 'Box: ' . $box;
        }
        if (preg_match('~/(efk_\d+)/~', '/' . $tail, $mm)) {
            $efk = (string)($mm[1] ?? '');
            $efk = substr($efk, 4);
            return 'E.F.K: ' . $efk;
        }
        if (preg_match('~/(check_[^/]+)/~', '/' . $tail, $mm)) {
            $chk = (string)($mm[1] ?? '');
            $chk = substr($chk, 6);
            $chk = str_replace('_', ' ', $chk);
            return 'Checklist: ' . $chk;
        }
    }
    return 'Unassigned';
};

$checkFields = [
    'fumigation_completed' => 'Fumigation Completed',
    'bait_box_checked' => 'Bait Box Checked',
    'glue_box_checked' => 'Glue Box Checked',
    'efk_checked' => "E.F.K's Checked",
    'ilt_checked' => "I.L.T 's Checked",
    'others_checked' => "Other's",
];

function table_exists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*)
         FROM information_schema.tables
         WHERE table_schema = DATABASE() AND table_name = :t'
    );
    $stmt->execute(['t' => $table]);
    return (int)$stmt->fetchColumn() > 0;
}

function load_task_images_from_dir(int $taskId): array
{
    $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
    $relDir = 'uploads/tasks/' . $taskId;
    $absDir = $uploadsRoot . '/' . $relDir;
    $out = [];
    if (is_dir($absDir)) {
        $allowedExt = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        $stack = [[$absDir, '/' . $relDir]];
        while ($stack) {
            [$curAbs, $curRel] = array_pop($stack);
            $list = scandir($curAbs);
            if (!is_array($list)) {
                continue;
            }
            foreach ($list as $f) {
                if ($f === '.' || $f === '..') {
                    continue;
                }
                $pAbs = $curAbs . '/' . $f;
                $pRel = $curRel . '/' . $f;
                if (is_dir($pAbs)) {
                    $stack[] = [$pAbs, $pRel];
                    continue;
                }
                if (!is_file($pAbs)) {
                    continue;
                }
                $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));
                if ($ext !== '' && in_array($ext, $allowedExt, true)) {
                    $out[] = $pRel;
                }
            }
        }
        rsort($out);
    }
    return $out;
}

try {
    $pdo = Database::pdo();

    if ($taskId > 0) {
        $stmt = $pdo->prepare(
            "SELECT
                t.task_id,
                t.scheduled_date,
                t.scheduled_time,
                t.status AS task_status,
                s.service_name,
                u.full_name AS staff_name,
                p.payment_status,
                p.amount,
                sr.request_id,
                sr.preferred_date,
                sr.preferred_time,
                sr.pest_type,
                sr.severity_level,
                sr.property_address
             FROM tasks t
             JOIN service_requests sr ON t.request_id = sr.request_id
             JOIN services s ON sr.service_id = s.service_id
             LEFT JOIN users u ON t.assigned_staff_id = u.user_id
             LEFT JOIN payments p ON p.request_id = sr.request_id
             WHERE sr.customer_id = :customer_id
               AND t.task_id = :task_id
             LIMIT 1"
        );
        $stmt->execute(['customer_id' => $customerId, 'task_id' => $taskId]);
        $report = $stmt->fetch();

        if (!$report) {
            $error = 'Report not found.';
        } else {
            $images = load_task_images_from_dir($taskId);

            try {
                $checklist = TaskChecklistService::get($pdo, $taskId);
            } catch (Throwable $e) {
                $checklist = null;
            }

            if (!$images && table_exists($pdo, 'task_images')) {
                try {
                    $stmtImgs = $pdo->prepare(
                        "SELECT
                            COALESCE(image_path, file_path, path) AS p
                         FROM task_images
                         WHERE task_id = :task_id
                         ORDER BY 1 DESC"
                    );
                    $stmtImgs->execute(['task_id' => $taskId]);
                    $imgs = $stmtImgs->fetchAll(PDO::FETCH_COLUMN);
                    foreach ($imgs as $p) {
                        if ($p) {
                            $images[] = (string)$p;
                        }
                    }
                } catch (Throwable $e) {
                    // Ignore if columns differ.
                }
            }
        }
    } else {
        $sql =
            "SELECT
                t.task_id,
                t.scheduled_date,
                t.scheduled_time,
                t.status AS task_status,
                s.service_name,
                u.full_name AS staff_name,
                p.payment_status,
                p.amount
             FROM tasks t
             JOIN service_requests sr ON t.request_id = sr.request_id
             JOIN services s ON sr.service_id = s.service_id
             LEFT JOIN users u ON t.assigned_staff_id = u.user_id
             LEFT JOIN payments p ON p.request_id = sr.request_id
             WHERE sr.customer_id = :customer_id
               AND t.status = 'completed'";

        $params = ['customer_id' => $customerId];
        if ($q !== '') {
            $sql .= ' AND (s.service_name LIKE :q OR u.full_name LIKE :q)';
            $params['q'] = '%' . $q . '%';
        }

        $sql .= ' ORDER BY t.scheduled_date DESC, t.scheduled_time DESC, t.task_id DESC';

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $rows = $stmt->fetchAll();
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => Constants::APP_ROOT . '/customer/overview.php', 'active' => false],
    ['label' => 'My Requests', 'href' => Constants::APP_ROOT . '/customer/index.php', 'active' => false],
    ['label' => 'Request Service', 'href' => Constants::APP_ROOT . '/customer/request_service.php', 'active' => false],
    ['label' => 'My Services', 'href' => Constants::APP_ROOT . '/customer/my_services.php', 'active' => false],
    ['label' => 'Service Reports', 'href' => Constants::APP_ROOT . '/customer/reports.php', 'active' => true],
    ['label' => 'IPM Map', 'href' => Constants::APP_ROOT . '/customer/ipm_map.php', 'active' => false],
    ['label' => 'Gap Analysis Report', 'href' => Constants::APP_ROOT . '/customer/gap_analysis_report.php', 'active' => false],
    ['label' => 'Trend Analysis Report', 'href' => Constants::APP_ROOT . '/customer/trend_analysis_report.php', 'active' => false],
    ['label' => 'Complaints', 'href' => Constants::APP_ROOT . '/customer/complaints.php', 'active' => false],
    ['label' => 'Payments', 'href' => Constants::APP_ROOT . '/customer/payments.php', 'active' => false],
];

ob_start();
?>
<?php if ($error !== ''): ?>
    <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
        <?= e($error) ?>
    </div>
<?php endif; ?>

<?php if ($taskId > 0 && $report): ?>
    <div class="rounded-xl border bg-white p-6">
        <div class="flex items-start justify-between gap-4">
            <div>
                <h1 class="text-xl font-semibold">Service Report</h1>
                <p class="mt-1 text-sm text-slate-600">Report for completed task #<?= e((string)$report['task_id']) ?>.</p>
            </div>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/customer/reports.php">Back</a>
        </div>

        <div class="mt-6 grid grid-cols-1 gap-6 lg:grid-cols-2">
            <div class="rounded-xl border bg-slate-50 p-4">
                <div class="text-xs font-medium text-slate-600">Service</div>
                <div class="mt-2 text-sm">
                    <div><span class="text-slate-500">Service:</span> <span class="font-medium"><?= e((string)$report['service_name']) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Staff:</span> <span class="font-medium"><?= e((string)($report['staff_name'] ?? '')) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Schedule:</span> <span class="font-medium"><?= e((string)$report['scheduled_date']) ?> <?= e((string)$report['scheduled_time']) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Status:</span> <span class="font-medium"><?= e((string)$report['task_status']) ?></span></div>
                </div>
            </div>

            <div class="rounded-xl border bg-slate-50 p-4">
                <div class="text-xs font-medium text-slate-600">Request details</div>
                <div class="mt-2 text-sm">
                    <div><span class="text-slate-500">Pest type:</span> <span class="font-medium"><?= e((string)($report['pest_type'] ?? '')) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Severity:</span> <span class="font-medium"><?= e((string)($report['severity_level'] ?? '')) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Preferred:</span> <span class="font-medium"><?= e((string)($report['preferred_date'] ?? '')) ?> <?= e((string)($report['preferred_time'] ?? '')) ?></span></div>
                    <?php if (!empty($report['property_address'])): ?>
                        <div class="mt-1"><span class="text-slate-500">Address:</span> <span class="font-medium"><?= e((string)$report['property_address']) ?></span></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="mt-6 rounded-xl border bg-white p-4">
            <div class="text-sm font-semibold">Images</div>
            <div class="mt-3 grid grid-cols-2 gap-3 md:grid-cols-4">
                <?php if (!$images): ?>
                    <div class="col-span-full text-sm text-slate-500">No images uploaded for this task.</div>
                <?php else: ?>
                    <?php foreach ($images as $p): ?>
                        <?php $pub = $toPublic((string)$p); ?>
                        <?php $label = $imageDetailLabel((string)$p); ?>
                        <a class="block overflow-hidden rounded-lg border bg-white" href="<?= e((string)$pub) ?>" target="_blank" rel="noopener">
                            <img class="h-32 w-full object-cover" src="<?= e((string)$pub) ?>" alt="Task image">
                            <div class="border-t bg-slate-50 px-2 py-1 text-[11px] text-slate-600"><?= e((string)$label) ?></div>
                        </a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="mt-6 rounded-xl border bg-white p-4">
            <div class="text-sm font-semibold">Additional Checklist</div>
            <div class="mt-3 grid grid-cols-1 gap-2 md:grid-cols-2">
                <?php foreach ($checkFields as $k => $label): ?>
                    <?php $isChecked = $checklist ? !empty($checklist[$k]) : false; ?>
                    <div class="flex items-center justify-between rounded-lg border bg-slate-50 px-3 py-2 text-sm">
                        <div><?= e($label) ?></div>
                        <div class="font-medium <?= $isChecked ? 'text-green-700' : 'text-slate-500' ?>"><?= $isChecked ? 'Yes' : 'No' ?></div>
                    </div>
                <?php endforeach; ?>
            </div>

            <?php
                $othersText = $checklist ? trim((string)($checklist['others_text'] ?? '')) : '';
                $othersChecked = $checklist ? !empty($checklist['others_checked']) : false;
            ?>
            <?php if ($othersChecked && $othersText !== ''): ?>
                <div class="mt-3 rounded-lg border bg-white px-3 py-2 text-sm">
                    <div class="text-xs font-medium text-slate-600">Other's (details)</div>
                    <div class="mt-1 text-slate-800"><?= e($othersText) ?></div>
                </div>
            <?php endif; ?>
        </div>
    </div>
<?php else: ?>
    <div class="rounded-xl border bg-white p-6">
        <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
                <h1 class="text-xl font-semibold">Service Reports</h1>
                <p class="mt-1 text-sm text-slate-600">Reports are shown for completed services.</p>
            </div>
        </div>

        <form class="mt-5 flex gap-2" method="get" action="">
            <input class="w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900" type="text" name="q" value="<?= e($q) ?>" placeholder="Search by service or staff">
            <button class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" type="submit">Search</button>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/customer/reports.php">Reset</a>
        </form>

        <div class="mt-5 overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead class="text-left text-slate-600">
                    <tr class="border-b">
                        <th class="py-2 pr-4">Task</th>
                        <th class="py-2 pr-4">Service</th>
                        <th class="py-2 pr-4">Staff</th>
                        <th class="py-2 pr-4">Schedule</th>
                        <th class="py-2">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$rows): ?>
                        <tr class="border-b"><td class="py-3 text-slate-500" colspan="6">No completed services yet.</td></tr>
                    <?php else: ?>
                        <?php foreach ($rows as $r): ?>
                            <tr class="border-b last:border-0">
                                <td class="py-3 pr-4 font-medium">#<?= e((string)$r['task_id']) ?></td>
                                <td class="py-3 pr-4"><?= e((string)$r['service_name']) ?></td>
                                <td class="py-3 pr-4"><?= e((string)($r['staff_name'] ?? '')) ?></td>
                                <td class="py-3 pr-4"><?= e((string)($r['scheduled_date'] ?? '')) ?> <?= e((string)($r['scheduled_time'] ?? '')) ?></td>
                                <td class="py-3">
                                    <div class="flex flex-wrap gap-2">
                                        <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/customer/reports.php?task_id=<?= e((string)$r['task_id']) ?>">Report</a>
                                        <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/customer/task_details.php?id=<?= e((string)$r['task_id']) ?>">Details</a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>
<?php
$content = ob_get_clean();

require __DIR__ . '/../../includes/dashboard_layout.php';
