<?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);
$search = trim($_GET['search'] ?? '');

$active_company_id = isset($_SESSION['active_company_id']) && $_SESSION['active_company_id'] !== ''
    ? (int)$_SESSION['active_company_id']
    : null;

/*
|--------------------------------------------------------------------------
| Workspace logic
|--------------------------------------------------------------------------
*/
$workspace_type = $_GET['workspace'] ?? ($_SESSION['workspace_type'] ?? 'personal');

if ($workspace_type === 'company' && $active_company_id !== null) {
    $is_company_workspace = true;
    $_SESSION['workspace_type'] = 'company';
} else {
    $is_company_workspace = false;
    $_SESSION['workspace_type'] = 'personal';
}

$scope = $is_company_workspace ? 'company' : 'personal';

$today = date('Y-m-d');
$next_30_days = date('Y-m-d', strtotime('+30 days'));

function getDateStatus($date, $today, $next_30_days)
{
    if (empty($date)) {
        return ['label' => 'No Date', 'class' => 'no-date'];
    }

    if ($date < $today) {
        return ['label' => 'Expired / Overdue', 'class' => 'expired'];
    }

    if ($date <= $next_30_days) {
        return ['label' => 'Due Soon', 'class' => 'soon'];
    }

    return ['label' => 'OK', 'class' => 'ok'];
}

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

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

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

    return $date;
}

function bindOwnership(PDOStatement $stmt, bool $is_company_workspace, ?int $active_company_id, int $user_id): void
{
    if ($is_company_workspace) {
        $stmt->bindValue(":company_id", $active_company_id, PDO::PARAM_INT);
    } else {
        $stmt->bindValue(":user_id", $user_id, PDO::PARAM_INT);
    }
}

if ($is_company_workspace) {
    $ownershipSql = "company_id = :company_id";
} else {
    $ownershipSql = "user_id = :user_id AND company_id IS NULL";
}

if ($search !== '') {
    $stmt = $db->prepare("
        SELECT *
        FROM cars
        WHERE {$ownershipSql}
          AND (
              car_name LIKE :search
              OR plate_number LIKE :search
              OR brand LIKE :search
              OR model LIKE :search
              OR year LIKE :search
              OR note LIKE :search
          )
        ORDER BY id DESC
    ");

    $like = "%" . $search . "%";
    bindOwnership($stmt, $is_company_workspace, $active_company_id, $user_id);
    $stmt->bindValue(":search", $like, PDO::PARAM_STR);
} else {
    $stmt = $db->prepare("
        SELECT *
        FROM cars
        WHERE {$ownershipSql}
        ORDER BY id DESC
    ");

    bindOwnership($stmt, $is_company_workspace, $active_company_id, $user_id);
}

$stmt->execute();
$cars = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Cars</title>
    <link rel="stylesheet" href="assets/css/app.css">

    <style>
        .admin-table {
            width: 100%;
            min-width: 1100px;
        }

        .workspace-badge {
            display: inline-flex;
            align-items: center;
            padding: 8px 12px;
            border-radius: 999px;
            font-size: 13px;
            font-weight: 700;
            background: #eff8ff;
            color: #175cd3;
            border: 1px solid #b2ddff;
            margin-top: 12px;
        }

        @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>My Cars</h1>
                    <p>Manage your cars, insurance expiry dates, and service reminders.</p>
                    <div class="workspace-badge">
                        Viewing: <?php echo $is_company_workspace ? 'Company Workspace' : 'Personal Workspace'; ?>
                    </div>
                </div>
                <div class="welcome-badge">
                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?>
                </div>
            </div>
        </div>

        <div class="card">
            <form method="GET" class="menu">
                <input type="hidden" name="workspace" value="<?php echo htmlspecialchars($scope); ?>">
                <input type="hidden" name="scope" value="<?php echo htmlspecialchars($scope); ?>">

                <input
                    type="text"
                    name="search"
                    class="search-input"
                    placeholder="Search cars..."
                    value="<?php echo htmlspecialchars($search); ?>"
                >

                <button class="btn btn-primary" type="submit">Search</button>
                <a href="my_cars.php?workspace=<?php echo htmlspecialchars($scope); ?>&scope=<?php echo htmlspecialchars($scope); ?>" class="btn btn-secondary">Clear</a>
                <a href="add_car.php?workspace=<?php echo htmlspecialchars($scope); ?>&scope=<?php echo htmlspecialchars($scope); ?>" class="btn btn-success">Add Car</a>
            </form>
        </div>

        <div class="card">
            <div class="section-title">Car List</div>
            <div class="section-subtext">
                Total: <strong><?php echo count($cars); ?></strong> car(s)
                <?php echo $is_company_workspace ? 'in company workspace' : 'in personal workspace'; ?>
            </div>

            <div class="table-wrap">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Car Name</th>
                            <th>Plate Number</th>
                            <th>Brand</th>
                            <th>Model</th>
                            <th>Year</th>
                            <th>Insurance Expiry</th>
                            <th>Insurance Status</th>
                            <th>Service Due Date</th>
                            <th>Service Status</th>
                            <th>Note</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($cars)): ?>
                            <?php foreach ($cars as $car): ?>
                                <?php
                                    $insuranceStatus = getDateStatus($car['insurance_expiry'] ?? '', $today, $next_30_days);
                                    $serviceStatus = getDateStatus($car['service_due_date'] ?? '', $today, $next_30_days);
                                ?>
                                <tr>
                                    <td><span class="chip">#<?php echo (int)$car['id']; ?></span></td>
                                    <td><?php echo htmlspecialchars($car['car_name'] ?? '-'); ?></td>
                                    <td><span class="plate-text"><?php echo htmlspecialchars($car['plate_number'] ?? '-'); ?></span></td>
                                    <td><?php echo htmlspecialchars($car['brand'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars($car['model'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars($car['year'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars(formatDateForDisplay($car['insurance_expiry'] ?? '')); ?></td>
                                    <td>
                                        <span class="status-badge <?php echo htmlspecialchars($insuranceStatus['class']); ?>">
                                            <?php echo htmlspecialchars($insuranceStatus['label']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo htmlspecialchars(formatDateForDisplay($car['service_due_date'] ?? '')); ?></td>
                                    <td>
                                        <span class="status-badge <?php echo htmlspecialchars($serviceStatus['class']); ?>">
                                            <?php echo htmlspecialchars($serviceStatus['label']); ?>
                                        </span>
                                    </td>
                                    <td class="note-cell"><?php echo htmlspecialchars($car['note'] ?? '-'); ?></td>
                                    <td>
                                        <div class="action-group">
                                            <a class="btn btn-secondary btn-sm" href="edit_car.php?id=<?php echo (int)$car['id']; ?>&workspace=<?php echo htmlspecialchars($scope); ?>&scope=<?php echo htmlspecialchars($scope); ?>">Edit</a>
                                            <a class="btn btn-danger btn-sm"
                                               href="delete_car.php?id=<?php echo (int)$car['id']; ?>&workspace=<?php echo htmlspecialchars($scope); ?>&scope=<?php echo htmlspecialchars($scope); ?>"
                                               onclick="return confirm('Delete this car?');">
                                               Delete
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="12">
                                    <div class="empty-state">No cars found.</div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

</body>
</html>