<?php
session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || $_SESSION['role'] === 'guest') {
    header("Location: login.php");
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$user_id = (int) ($_SESSION['user_id'] ?? 0);
$today = new DateTime('today');
$todayStr = $today->format('Y-m-d');
$next30Str = (new DateTime('today +30 days'))->format('Y-m-d');

function formatDateForDisplay(?string $date): string
{
    $date = trim((string) $date);

    if ($date === '') {
        return '-';
    }

    $dt = DateTime::createFromFormat('Y-m-d', $date);
    return $dt ? $dt->format('d/m/Y') : $date;
}

function getDaysLeft(?string $date): ?int
{
    $date = trim((string) $date);

    if ($date === '') {
        return null;
    }

    $dt = DateTime::createFromFormat('Y-m-d', $date);
    if (!$dt) {
        return null;
    }

    $today = new DateTime('today');
    $interval = $today->diff($dt);

    if ($dt < $today) {
        return -((int) $interval->days);
    }

    return (int) $interval->days;
}

function formatDaysLeft(?string $date): string
{
    $daysLeft = getDaysLeft($date);

    if ($daysLeft === null) {
        return '-';
    }

    if ($daysLeft < 0) {
        return 'Expired ' . abs($daysLeft) . ' day(s) ago';
    }

    if ($daysLeft === 0) {
        return 'Due today';
    }

    return $daysLeft . ' day(s)';
}

function getDaysLeftClass(?string $date): string
{
    $daysLeft = getDaysLeft($date);

    if ($daysLeft === null) {
        return 'days-muted';
    }

    if ($daysLeft < 0) {
        return 'days-expired';
    }

    if ($daysLeft <= 30) {
        return 'days-danger';
    }

    if ($daysLeft <= 90) {
        return 'days-warning';
    }

    return 'days-safe';
}

function getOverallStatus(?string $date): string
{
    $daysLeft = getDaysLeft($date);

    if ($daysLeft === null) {
        return 'No Date';
    }

    if ($daysLeft < 0) {
        return 'Expired';
    }

    if ($daysLeft <= 30) {
        return 'Due Soon';
    }

    return 'Upcoming';
}

function getDocumentReminderMonths(?string $category): int
{
    $category = strtolower(trim((string) $category));
    return $category === 'passport' ? 10 : 3;
}

function shouldShowDocumentReminder(?string $expiryDate, ?string $category): bool
{
    $expiryDate = trim((string) $expiryDate);

    if ($expiryDate === '') {
        return false;
    }

    $expiry = DateTime::createFromFormat('Y-m-d', $expiryDate);
    if (!$expiry) {
        return false;
    }

    $reminderDate = clone $expiry;
    $reminderDate->modify('-' . getDocumentReminderMonths($category) . ' months');

    $today = new DateTime('today');

    return $today >= $reminderDate;
}

function shouldShowContractReminder(?string $expireDate): bool
{
    $expireDate = trim((string) $expireDate);

    if ($expireDate === '') {
        return false;
    }

    $expiry = DateTime::createFromFormat('Y-m-d', $expireDate);
    if (!$expiry) {
        return false;
    }

    $reminderDate = clone $expiry;
    $reminderDate->modify('-30 days');

    $today = new DateTime('today');

    return $today >= $reminderDate;
}

function shouldShowCarReminder(?string $date): bool
{
    $date = trim((string) $date);

    if ($date === '') {
        return false;
    }

    $target = DateTime::createFromFormat('Y-m-d', $date);
    if (!$target) {
        return false;
    }

    $next30 = new DateTime('today +30 days');

    return $target <= $next30;
}

$items = [];

/* =========================
   Documents
========================= */
$stmt = $db->prepare("
    SELECT d.*, c.car_name, c.plate_number
    FROM documents d
    LEFT JOIN cars c ON d.car_id = c.id
    WHERE d.user_id = :user_id
    ORDER BY d.expiry_date ASC, d.id DESC
");
$stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();
$documents = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($documents as $doc) {
    $expiryDate = $doc['expiry_date'] ?? '';

    if (!shouldShowDocumentReminder($expiryDate, $doc['category'] ?? '')) {
        continue;
    }

    $name = trim((string) ($doc['custom_name'] ?? ''));
    if ($name === '') {
        $name = trim((string) ($doc['category'] ?? 'Document'));
    }

    $detailParts = [];

    if (!empty($doc['document_number'])) {
        $detailParts[] = 'No: ' . $doc['document_number'];
    }

    if (!empty($doc['car_name'])) {
        $carLabel = $doc['car_name'];
        if (!empty($doc['plate_number'])) {
            $carLabel .= ' (' . $doc['plate_number'] . ')';
        }
        $detailParts[] = 'Car: ' . $carLabel;
    }

    $items[] = [
        'source_type' => 'Document',
        'category' => $doc['category'] ?? '-',
        'name' => $name,
        'detail' => !empty($detailParts) ? implode(' | ', $detailParts) : '-',
        'date' => $expiryDate,
        'status' => getOverallStatus($expiryDate),
        'days_text' => formatDaysLeft($expiryDate),
        'days_class' => getDaysLeftClass($expiryDate),
        'view_url' => $doc['file_path'] ?? '',
        'edit_url' => 'edit_document.php?id=' . (int) $doc['id'],
    ];
}

/* =========================
   Cars
========================= */
$stmt = $db->prepare("
    SELECT *
    FROM cars
    WHERE user_id = :user_id
    ORDER BY id DESC
");
$stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();
$cars = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($cars as $car) {
    $carName = trim((string) ($car['car_name'] ?? 'Car'));
    $plate = trim((string) ($car['plate_number'] ?? ''));
    $carLabel = $carName . ($plate !== '' ? ' (' . $plate . ')' : '');

    if (shouldShowCarReminder($car['insurance_expiry'] ?? '')) {
        $date = $car['insurance_expiry'];

        $items[] = [
            'source_type' => 'Car',
            'category' => 'Insurance',
            'name' => $carLabel,
            'detail' => 'Insurance Expiry',
            'date' => $date,
            'status' => getOverallStatus($date),
            'days_text' => formatDaysLeft($date),
            'days_class' => getDaysLeftClass($date),
            'view_url' => '',
            'edit_url' => 'edit_car.php?id=' . (int) $car['id'],
        ];
    }

    if (shouldShowCarReminder($car['service_due_date'] ?? '')) {
        $date = $car['service_due_date'];

        $items[] = [
            'source_type' => 'Car',
            'category' => 'Service',
            'name' => $carLabel,
            'detail' => 'Service Due Date',
            'date' => $date,
            'status' => getOverallStatus($date),
            'days_text' => formatDaysLeft($date),
            'days_class' => getDaysLeftClass($date),
            'view_url' => '',
            'edit_url' => 'edit_car.php?id=' . (int) $car['id'],
        ];
    }
}

/* =========================
   Contracts
========================= */
$stmt = $db->prepare("
    SELECT *
    FROM contracts
    WHERE user_id = :user_id
    ORDER BY expire_date ASC, id DESC
");
$stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();
$contracts = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($contracts as $contract) {
    $expireDate = $contract['expire_date'] ?? '';

    if (!shouldShowContractReminder($expireDate)) {
        continue;
    }

    $detailParts = [];

    if (!empty($contract['customer_name'])) {
        $detailParts[] = 'Customer: ' . $contract['customer_name'];
    }

    if (!empty($contract['contract_number'])) {
        $detailParts[] = 'No: ' . $contract['contract_number'];
    }

    $items[] = [
        'source_type' => 'Contract',
        'category' => 'Contract',
        'name' => $contract['contract_title'] ?? 'Contract',
        'detail' => !empty($detailParts) ? implode(' | ', $detailParts) : '-',
        'date' => $expireDate,
        'status' => getOverallStatus($expireDate),
        'days_text' => formatDaysLeft($expireDate),
        'days_class' => getDaysLeftClass($expireDate),
        'view_url' => $contract['file_path'] ?? '',
        'edit_url' => 'edit_contract.php?id=' . (int) $contract['id'],
    ];
}

/* =========================
   Sort all reminders
========================= */
usort($items, function ($a, $b) {
    $dateA = $a['date'] ?? '';
    $dateB = $b['date'] ?? '';

    if ($dateA === $dateB) {
        return strcmp($a['source_type'], $b['source_type']);
    }

    return strcmp($dateA, $dateB);
});

$totalCount = count($items);
$documentCount = count(array_filter($items, fn($item) => $item['source_type'] === 'Document'));
$carCount = count(array_filter($items, fn($item) => $item['source_type'] === 'Car'));
$contractCount = count(array_filter($items, fn($item) => $item['source_type'] === 'Contract'));
$expiredCount = count(array_filter($items, fn($item) => $item['status'] === 'Expired'));
$dueSoonCount = count(array_filter($items, fn($item) => $item['status'] === 'Due Soon'));
$upcomingCount = count(array_filter($items, fn($item) => $item['status'] === 'Upcoming'));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reminders</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <style>
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 12px;
            margin-bottom: 18px;
        }

        .summary-card {
            background: #fff;
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            padding: 16px;
            box-shadow: 0 8px 24px rgba(16, 24, 40, 0.06);
        }

        .summary-card .label {
            font-size: 13px;
            color: #667085;
            margin-bottom: 6px;
        }

        .summary-card .value {
            font-size: 28px;
            font-weight: 700;
            color: #101828;
        }

        .table-wrap {
            width: 100%;
            overflow-x: auto;
        }

        .admin-table {
            width: 100%;
            min-width: 1050px;
        }

        .admin-table th,
        .admin-table td {
            white-space: nowrap;
            padding: 10px 12px;
            font-size: 13px;
            vertical-align: middle;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-expired {
            background: #fef3f2;
            color: #b42318;
        }

        .status-soon {
            background: #fff7e6;
            color: #b54708;
        }

        .status-upcoming {
            background: #ecfdf3;
            color: #027a48;
        }

        .status-muted {
            background: #f2f4f7;
            color: #667085;
        }

        .days-badge {
            display: inline-block;
            padding: 6px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: 600;
        }

        .days-expired {
            background: #fef3f2;
            color: #b42318;
        }

        .days-danger {
            background: #fff7e6;
            color: #b54708;
        }

        .days-warning {
            background: #fffaeb;
            color: #b54708;
        }

        .days-safe {
            background: #ecfdf3;
            color: #027a48;
        }

        .days-muted {
            background: #f2f4f7;
            color: #667085;
        }

        .action-group {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
        }

        @media (max-width: 768px) {
            .admin-table {
                min-width: 980px;
            }
        }
    </style>
</head>
<body>

<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Reminders Dashboard</h1>
                    <p>Track upcoming and expired items from documents, cars, and contracts.</p>
                </div>
                <div class="welcome-badge">
                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?>
                </div>
            </div>
        </div>

        <div class="summary-grid">
            <div class="summary-card">
                <div class="label">Total Reminders</div>
                <div class="value"><?php echo $totalCount; ?></div>
            </div>
            <div class="summary-card">
                <div class="label">Documents</div>
                <div class="value"><?php echo $documentCount; ?></div>
            </div>
            <div class="summary-card">
                <div class="label">Cars</div>
                <div class="value"><?php echo $carCount; ?></div>
            </div>
            <div class="summary-card">
                <div class="label">Contracts</div>
                <div class="value"><?php echo $contractCount; ?></div>
            </div>
            <div class="summary-card">
                <div class="label">Expired</div>
                <div class="value"><?php echo $expiredCount; ?></div>
            </div>
            <div class="summary-card">
                <div class="label">Due Soon</div>
                <div class="value"><?php echo $dueSoonCount; ?></div>
            </div>
        </div>

        <div class="card">
            <div style="display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap; margin-bottom:12px;">
                <div>
                    <div class="section-title">Upcoming Events</div>
                    <div class="section-subtext">
                        Total: <strong><?php echo $totalCount; ?></strong> item(s)
                    </div>
                </div>
            </div>

            <div class="table-wrap">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>Type</th>
                            <th>Category</th>
                            <th>Name</th>
                            <th>Detail</th>
                            <th>Date</th>
                            <th>Days Left</th>
                            <th>Status</th>
                            <th>File</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($items)): ?>
                            <?php foreach ($items as $item): ?>
                                <?php
                                    $statusClass = 'status-muted';

                                    if ($item['status'] === 'Expired') {
                                        $statusClass = 'status-expired';
                                    } elseif ($item['status'] === 'Due Soon') {
                                        $statusClass = 'status-soon';
                                    } elseif ($item['status'] === 'Upcoming') {
                                        $statusClass = 'status-upcoming';
                                    }
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($item['source_type']); ?></td>
                                    <td><?php echo htmlspecialchars($item['category']); ?></td>
                                    <td><?php echo htmlspecialchars($item['name']); ?></td>
                                    <td><?php echo htmlspecialchars($item['detail']); ?></td>
                                    <td><?php echo htmlspecialchars(formatDateForDisplay($item['date'])); ?></td>
                                    <td>
                                        <span class="days-badge <?php echo htmlspecialchars($item['days_class']); ?>">
                                            <?php echo htmlspecialchars($item['days_text']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="status-badge <?php echo htmlspecialchars($statusClass); ?>">
                                            <?php echo htmlspecialchars($item['status']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if (!empty($item['view_url'])): ?>
                                            <a class="link-btn" href="<?php echo htmlspecialchars($item['view_url']); ?>" target="_blank">View</a>
                                        <?php else: ?>
                                            <span class="muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="action-group">
                                            <a class="btn btn-secondary btn-sm" href="<?php echo htmlspecialchars($item['edit_url']); ?>">Edit</a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="9">
                                    <div class="empty-state">No reminders found.</div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

</body>
</html>