<?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 = 'Edit Customer Report';

$reportId = (int)($_GET['report_id'] ?? ($_POST['report_id'] ?? 0));
$customerId = (int)($_GET['customer_id'] ?? ($_POST['customer_id'] ?? 0));
$type = (string)($_GET['type'] ?? ($_POST['type'] ?? CustomerReportsService::TYPE_IPM_MAP));

$error = '';
$success = '';

$row = null;
$customer = null;

$monthRaw = (string)($_POST['month'] ?? '');

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

    if ($reportId <= 0 || $customerId <= 0) {
        throw new RuntimeException('Missing report.');
    }

    $stmt = $pdo->prepare(
        "SELECT report_id, customer_id, report_type, report_month, file_path, mime_type, uploaded_at
         FROM customer_reports WHERE report_id = :id LIMIT 1"
    );
    $stmt->execute(['id' => $reportId]);
    $row = $stmt->fetch();

    if (!$row || (int)$row['customer_id'] !== $customerId) {
        throw new RuntimeException('Report not found.');
    }

    $stmtC = $pdo->prepare("SELECT user_id, full_name, email FROM users WHERE user_id = :id AND user_type = 'customer' LIMIT 1");
    $stmtC->execute(['id' => $customerId]);
    $customer = $stmtC->fetch();

    $type = (string)$row['report_type'];

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $newMonth = null;
        if ($type !== CustomerReportsService::TYPE_IPM_MAP) {
            $norm = CustomerReportsService::normalizeMonth($monthRaw);
            if ($norm === null) {
                $error = 'Please select a valid month.';
            } else {
                $newMonth = $norm;
            }
        }

        if ($error === '') {
            // Enforce unique month per customer+type (exclude current row)
            if ($type !== CustomerReportsService::TYPE_IPM_MAP) {
                $stmtChk = $pdo->prepare(
                    'SELECT COUNT(*) FROM customer_reports
                     WHERE customer_id = :cid AND report_type = :t AND report_month = :m AND report_id <> :rid'
                );
                $stmtChk->execute([
                    'cid' => $customerId,
                    't' => $type,
                    'm' => $newMonth,
                    'rid' => $reportId,
                ]);
                if ((int)$stmtChk->fetchColumn() > 0) {
                    $error = 'A report for this month already exists for this customer.';
                }
            }
        }

        $newPath = null;
        $newMime = null;

        if ($error === '' && isset($_FILES['report']) && (int)($_FILES['report']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
            if ((int)($_FILES['report']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
                $error = 'File upload failed.';
            } else {
                $maxBytes = 12 * 1024 * 1024;
                if ((int)($_FILES['report']['size'] ?? 0) <= 0 || (int)($_FILES['report']['size'] ?? 0) > $maxBytes) {
                    $error = 'File must be less than 12MB.';
                } else {
                    $finfo = new finfo(FILEINFO_MIME_TYPE);
                    $mime = (string)$finfo->file((string)($_FILES['report']['tmp_name'] ?? ''));
                    $ext = CustomerReportsService::allowedMimeToExt($mime);
                    if ($ext === null) {
                        $error = 'Only PDF or image files (JPG, PNG, WEBP, GIF) are allowed.';
                    } else {
                        $uploadsRoot = realpath(__DIR__ . '/../../assets') ?: (__DIR__ . '/../../assets');
                        $relDir = 'uploads/customer_reports/' . $customerId . '/' . $type;
                        $absDir = rtrim($uploadsRoot, '/\\') . '/' . $relDir;
                        if (!is_dir($absDir)) {
                            if (!mkdir($absDir, 0775, true) && !is_dir($absDir)) {
                                $error = 'Failed to create upload directory.';
                            }
                        }

                        if ($error === '') {
                            $prefix = $newMonth ? str_replace('-', '', substr($newMonth, 0, 7)) . '_' : '';
                            $safeName = $prefix . bin2hex(random_bytes(16)) . '.' . $ext;
                            $absPath = $absDir . '/' . $safeName;
                            $newPath = Constants::ASSET_ROOT . '/' . $relDir . '/' . $safeName;
                            $newMime = $mime;

                            if (!move_uploaded_file((string)($_FILES['report']['tmp_name'] ?? ''), $absPath)) {
                                $error = 'Failed to save uploaded file.';
                                $newPath = null;
                                $newMime = null;
                            }
                        }
                    }
                }
            }
        }

        if ($error === '') {
            $stored = (string)($row['file_path'] ?? '');

            if ($type !== CustomerReportsService::TYPE_IPM_MAP) {
                $stmtUpd = $pdo->prepare('UPDATE customer_reports SET report_month = :m WHERE report_id = :id');
                $stmtUpd->execute(['m' => $newMonth, 'id' => $reportId]);
            }

            if ($newPath !== null && $newMime !== null) {
                $stmtUpdFile = $pdo->prepare('UPDATE customer_reports SET file_path = :p, mime_type = :mime, uploaded_at = :at WHERE report_id = :id');
                $stmtUpdFile->execute([
                    'p' => $newPath,
                    'mime' => $newMime,
                    'at' => date('Y-m-d H:i:s'),
                    'id' => $reportId,
                ]);

                // delete old file safely
                $deleteCandidates = [];
                if (str_starts_with($stored, Constants::ASSET_ROOT . '/')) {
                    $rel = substr($stored, strlen(Constants::ASSET_ROOT));
                    $base = realpath(__DIR__ . '/../../assets') ?: (__DIR__ . '/../../assets');
                    $deleteCandidates[] = rtrim($base, '/\\') . $rel;
                } elseif (str_starts_with($stored, Constants::APP_ROOT . '/')) {
                    $rel = substr($stored, strlen(Constants::APP_ROOT));
                    $base = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
                    $deleteCandidates[] = rtrim($base, '/\\') . $rel;
                } elseif (str_starts_with($stored, '/uploads/')) {
                    $assetBase = realpath(__DIR__ . '/../../assets') ?: (__DIR__ . '/../../assets');
                    $publicBase = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
                    $deleteCandidates[] = rtrim($assetBase, '/\\') . $stored;
                    $deleteCandidates[] = rtrim($publicBase, '/\\') . $stored;
                }

                foreach ($deleteCandidates as $abs) {
                    $real = realpath($abs);
                    if ($real === false) {
                        continue;
                    }

                    $assetsRoot = realpath(__DIR__ . '/../../assets') ?: (__DIR__ . '/../../assets');
                    $publicRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');

                    $assetsRoot = rtrim(str_replace('\\', '/', $assetsRoot), '/');
                    $publicRoot = rtrim(str_replace('\\', '/', $publicRoot), '/');
                    $realNorm = str_replace('\\', '/', $real);

                    $isInsideAssets = str_starts_with($realNorm, $assetsRoot . '/uploads/');
                    $isInsidePublic = str_starts_with($realNorm, $publicRoot . '/uploads/');

                    if ($isInsideAssets || $isInsidePublic) {
                        @unlink($real);
                    }
                }
            }

            header('Location: /pest/public/admin/customer_reports_view.php?customer_id=' . $customerId . '&type=' . urlencode($type));
            exit;
        }
    }
} catch (Throwable $e) {
    $error = $error !== '' ? $error : $e->getMessage();
}

$currentMonth = '';
if ($row && !empty($row['report_month'])) {
    $currentMonth = date('Y-m', strtotime((string)$row['report_month']));
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => '/pest/public/admin/customers.php', 'active' => true],
    ['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],
];

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; ?>

<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">Edit Report</h1>
            <?php if ($customer): ?>
                <p class="mt-1 text-sm text-slate-600">
                    <?= e((string)$customer['full_name']) ?> (<?= e((string)$customer['email']) ?>) — Customer #<?= e((string)$customer['user_id']) ?>
                </p>
            <?php endif; ?>
            <?php if ($row): ?>
                <p class="mt-1 text-sm text-slate-600"><?= e(CustomerReportsService::typeLabel((string)$row['report_type'])) ?></p>
            <?php endif; ?>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/customer_reports_view.php?customer_id=<?= e((string)$customerId) ?>&type=<?= e((string)$type) ?>">Back</a>
    </div>

    <?php if ($row): ?>
        <form class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2" method="post" action="" enctype="multipart/form-data">
            <input type="hidden" name="report_id" value="<?= e((string)$reportId) ?>">
            <input type="hidden" name="customer_id" value="<?= e((string)$customerId) ?>">
            <input type="hidden" name="type" value="<?= e((string)$type) ?>">

            <?php if ((string)$row['report_type'] !== CustomerReportsService::TYPE_IPM_MAP): ?>
                <div>
                    <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($currentMonth) ?>" required>
                </div>
            <?php else: ?>
                <div class="text-sm text-slate-600 md:col-span-2">
                    IPM Map does not use a month. You can replace the file below.
                </div>
            <?php endif; ?>

            <div class="md:col-span-2">
                <label class="block text-sm font-medium">Replace file (optional)</label>
                <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="file" name="report" accept="application/pdf,image/*">
                <div class="mt-1 text-xs text-slate-500">If you upload a new file, the old one will be deleted.</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">Save</button>
            </div>
        </form>
    <?php endif; ?>
</div>
<?php
$content = ob_get_clean();

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