<?php

declare(strict_types=1);

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

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

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

$user = auth_user();
$title = 'Upload Customer Reports';

$pdo = null;
$error = '';
$success = '';

$customerId = (int)($_GET['customer_id'] ?? ($_POST['customer_id'] ?? 0));
$type = (string)($_GET['type'] ?? ($_POST['type'] ?? CustomerReportsService::TYPE_IPM_MAP));
$monthRaw = (string)($_GET['month'] ?? ($_POST['month'] ?? date('Y-m')));
$month = CustomerReportsService::normalizeMonth($monthRaw);

$customers = [];
$existing = [];

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

    $customers = $pdo->query(
        "SELECT user_id, full_name, email
         FROM users
         WHERE user_type = 'customer'
         ORDER BY full_name ASC, user_id ASC"
    )->fetchAll();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $error === '') {
    if ($customerId <= 0) {
        $error = 'Please select a customer.';
    } elseif (!isset($_FILES['report'])) {
        $error = 'Please choose a file to upload.';
    } else {
        $uploadedBy = (int)($user['user_id'] ?? 0);
        [$ok, $msg] = CustomerReportsService::saveUpload($pdo, $customerId, $type, $month, $_FILES['report'], $uploadedBy);
        if (!$ok) {
            $error = $msg;
        } else {
            $success = $msg;
            $redirectMonth = $type === CustomerReportsService::TYPE_IPM_MAP ? '' : ('&month=' . urlencode($monthRaw));
            header('Location: /pest/public/admin/customer_reports_upload.php?customer_id=' . $customerId . '&type=' . urlencode($type) . $redirectMonth);
            exit;
        }
    }
}

if ($pdo instanceof PDO && $customerId > 0 && $error === '') {
    try {
        $existing = CustomerReportsService::listReports($pdo, $customerId, $type);
    } catch (Throwable $e) {
        $existing = [];
    }
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => '/pest/public/admin/customers.php', 'active' => false],
    ['label' => 'Staff', 'href' => '/pest/public/admin/staff.php', 'active' => false],
    ['label' => 'Staff Locations', 'href' => '/pest/public/admin/staff_locations.php', 'active' => false],
    ['label' => 'Services', 'href' => '/pest/public/admin/services.php', 'active' => false],
    ['label' => 'Task Assignment', 'href' => '/pest/public/admin/task_assignment.php', 'active' => false],
    ['label' => 'Payments', 'href' => '/pest/public/admin/payments.php', 'active' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/admin/complaints.php', 'active' => false],
    ['label' => 'Reports', 'href' => '/pest/public/admin/reports.php', 'active' => false],
];

$types = [
    CustomerReportsService::TYPE_IPM_MAP,
    CustomerReportsService::TYPE_GAP_ANALYSIS,
    CustomerReportsService::TYPE_TREND_ANALYSIS,
];

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 ($success !== ''): ?>
    <div class="rounded-xl border border-green-200 bg-green-50 p-4 text-sm text-green-700">
        <?= e($success) ?>
    </div>
<?php endif; ?>

<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">Upload Customer Reports</h1>
            <p class="mt-1 text-sm text-slate-600">Upload IPM Map (once) or monthly Gap/Trend Analysis reports per customer.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/reports.php">Back</a>
    </div>

    <form class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2" method="post" action="" enctype="multipart/form-data">
        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Customer</label>
            <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="customer_id" required>
                <option value="">Choose a customer</option>
                <?php foreach ($customers as $c): ?>
                    <option value="<?= e((string)$c['user_id']) ?>" <?= ((int)$customerId === (int)$c['user_id']) ? 'selected' : '' ?>>
                        #<?= e((string)$c['user_id']) ?> - <?= e((string)$c['full_name']) ?> (<?= e((string)$c['email']) ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div>
            <label class="block text-sm font-medium">Report Type</label>
            <select id="reportType" class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="type" required>
                <?php foreach ($types as $t): ?>
                    <option value="<?= e($t) ?>" <?= ($type === $t) ? 'selected' : '' ?>><?= e(CustomerReportsService::typeLabel($t)) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div id="monthWrap">
            <label class="block text-sm font-medium">Month</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="month" name="month" value="<?= e($monthRaw) ?>">
            <div class="mt-1 text-xs text-slate-500">Required for Gap/Trend reports.</div>
        </div>

        <div class="md:col-span-2">
            <label class="block text-sm font-medium">File (PDF or Image)</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="file" name="report" accept="application/pdf,image/*" required>
            <div class="mt-1 text-xs text-slate-500">Max 12MB. Allowed: PDF, JPG, PNG, WEBP, GIF.</div>
        </div>

        <div class="md:col-span-2">
            <button class="w-full rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" type="submit">Upload</button>
        </div>
    </form>

    <?php if ($customerId > 0): ?>
        <div class="mt-8">
            <div class="flex items-center justify-between">
                <div class="text-sm font-semibold">Existing Uploads</div>
                <div class="text-xs text-slate-500"><?= e(CustomerReportsService::typeLabel($type)) ?></div>
            </div>

            <div class="mt-3 grid grid-cols-2 gap-3 md:grid-cols-4">
                <?php if (!$existing): ?>
                    <div class="col-span-full text-sm text-slate-500">No uploads for this customer and report type.</div>
                <?php else: ?>
                    <?php foreach ($existing as $r): ?>
                        <?php
                            $p = CustomerReportsService::publicUrl((string)$r['file_path']);
                            $mime = (string)($r['mime_type'] ?? '');
                            $isPdf = (stripos($mime, 'pdf') !== false) || (strtolower(pathinfo($p, PATHINFO_EXTENSION)) === 'pdf');
                            $label = '';
                            if (!empty($r['report_month'])) {
                                $label = date('Y-m', strtotime((string)$r['report_month']));
                            } else {
                                $label = date('Y-m-d', strtotime((string)$r['uploaded_at']));
                            }
                        ?>
                        <a class="block overflow-hidden rounded-lg border bg-white" href="<?= e($p) ?>" target="_blank" rel="noopener">
                            <?php if ($isPdf): ?>
                                <div class="h-32 w-full bg-slate-50 flex items-center justify-center text-slate-600 text-xs font-medium">PDF</div>
                            <?php else: ?>
                                <img class="h-32 w-full object-cover" src="<?= e($p) ?>" alt="Report">
                            <?php endif; ?>
                            <div class="border-t px-2 py-1 text-[11px] text-slate-600"><?= e($label) ?></div>
                        </a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
    (function () {
        var sel = document.getElementById('reportType');
        var wrap = document.getElementById('monthWrap');
        function sync() {
            if (!sel || !wrap) return;
            var v = sel.value || '';
            var needsMonth = (v === 'gap_analysis_report' || v === 'trend_analysis_report');
            wrap.style.display = needsMonth ? '' : 'none';
        }
        sel && sel.addEventListener('change', sync);
        sync();
    })();
</script>
<?php
$content = ob_get_clean();

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