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

/*
|--------------------------------------------------------------------------
| Workspace logic
|--------------------------------------------------------------------------
*/
$workspace_type = $_SESSION['workspace_type'] ?? 'personal';
$active_company_id = isset($_SESSION['active_company_id']) && $_SESSION['active_company_id'] !== ''
    ? (int) $_SESSION['active_company_id']
    : null;

$is_company_workspace = ($workspace_type === 'company' && $active_company_id !== null);

$message = "";
$message_color = "green";

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid car ID.");
}

$id = (int) $_GET['id'];

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);
    }
}

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

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

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

    return null;
}

function formatDateForInput(?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 '';
}

/*
|--------------------------------------------------------------------------
| Ownership logic
|--------------------------------------------------------------------------
*/
if ($is_company_workspace) {
    $ownershipSql = "id = :id AND company_id = :company_id";
} else {
    $ownershipSql = "id = :id AND user_id = :user_id AND company_id IS NULL";
}

$stmt = $db->prepare("
    SELECT *
    FROM cars
    WHERE {$ownershipSql}
    LIMIT 1
");
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
bindOwnership($stmt, $is_company_workspace, $active_company_id, $user_id);
$stmt->execute();
$car = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$car) {
    die("Car not found.");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $car_name = trim($_POST['car_name'] ?? '');
    $plate_number = trim($_POST['plate_number'] ?? '');
    $brand = trim($_POST['brand'] ?? '');
    $model = trim($_POST['model'] ?? '');
    $year = trim($_POST['year'] ?? '');

    $insurance_expiry_raw = trim($_POST['insurance_expiry'] ?? '');
    $service_due_date_raw = trim($_POST['service_due_date'] ?? '');

    $insurance_expiry = convertToSqlDate($insurance_expiry_raw);
    $service_due_date = convertToSqlDate($service_due_date_raw);

    $note = trim($_POST['note'] ?? '');

    if ($car_name === '' || $plate_number === '') {
        $message = "Car name and plate number are required.";
        $message_color = "red";
    } elseif ($insurance_expiry_raw !== '' && $insurance_expiry === null) {
        $message = "Insurance expiry date is invalid. Please use dd/mm/yyyy.";
        $message_color = "red";
    } elseif ($service_due_date_raw !== '' && $service_due_date === null) {
        $message = "Service due date is invalid. Please use dd/mm/yyyy.";
        $message_color = "red";
    } else {
        if ($year === '') {
            $year = null;
        }

        if ($is_company_workspace) {
            $update = $db->prepare("
                UPDATE cars SET
                    car_name = :car_name,
                    plate_number = :plate_number,
                    brand = :brand,
                    model = :model,
                    year = :year,
                    insurance_expiry = :insurance_expiry,
                    service_due_date = :service_due_date,
                    note = :note
                WHERE id = :id AND company_id = :company_id
            ");
        } else {
            $update = $db->prepare("
                UPDATE cars SET
                    car_name = :car_name,
                    plate_number = :plate_number,
                    brand = :brand,
                    model = :model,
                    year = :year,
                    insurance_expiry = :insurance_expiry,
                    service_due_date = :service_due_date,
                    note = :note
                WHERE id = :id AND user_id = :user_id AND company_id IS NULL
            ");
        }

        bindOwnership($update, $is_company_workspace, $active_company_id, $user_id);

        $update->bindValue(":car_name", $car_name, PDO::PARAM_STR);
        $update->bindValue(":plate_number", $plate_number, PDO::PARAM_STR);
        $update->bindValue(":brand", $brand, PDO::PARAM_STR);
        $update->bindValue(":model", $model, PDO::PARAM_STR);

        if ($year === null) {
            $update->bindValue(":year", null, PDO::PARAM_NULL);
        } else {
            $update->bindValue(":year", $year, PDO::PARAM_STR);
        }

        if ($insurance_expiry === null) {
            $update->bindValue(":insurance_expiry", null, PDO::PARAM_NULL);
        } else {
            $update->bindValue(":insurance_expiry", $insurance_expiry, PDO::PARAM_STR);
        }

        if ($service_due_date === null) {
            $update->bindValue(":service_due_date", null, PDO::PARAM_NULL);
        } else {
            $update->bindValue(":service_due_date", $service_due_date, PDO::PARAM_STR);
        }

        $update->bindValue(":note", $note, PDO::PARAM_STR);
        $update->bindValue(":id", $id, PDO::PARAM_INT);

        if ($update->execute()) {
            $message = "Car updated successfully.";
            $message_color = "green";

            $stmt = $db->prepare("
                SELECT *
                FROM cars
                WHERE {$ownershipSql}
                LIMIT 1
            ");
            $stmt->bindValue(":id", $id, PDO::PARAM_INT);
            bindOwnership($stmt, $is_company_workspace, $active_company_id, $user_id);
            $stmt->execute();
            $car = $stmt->fetch(PDO::FETCH_ASSOC);
        } else {
            $message = "Update failed.";
            $message_color = "red";
        }
    }
}

$insurance_expiry_value = formatDateForInput($car['insurance_expiry'] ?? '');
$service_due_date_value = formatDateForInput($car['service_due_date'] ?? '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Car</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <style>
        .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;
        }
    </style>
</head>
<body>
<div class="layout">

    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Edit Car</h1>
                    <p>Update car information, service dates, and insurance dates.</p>
                    <div class="workspace-badge">
                        Viewing: <?php echo $is_company_workspace ? 'Company Workspace' : 'Personal Workspace'; ?>
                    </div>
                </div>
                <div class="welcome-badge">
                    #<?php echo (int)$car['id']; ?>
                </div>
            </div>
        </div>

        <?php if ($message !== ''): ?>
            <div class="alert-box <?php echo $message_color === 'green' ? 'alert-success' : 'alert-danger'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="section-title">Car Details</div>
            <div class="section-subtext">Edit the fields below and save your changes.</div>

            <form method="POST">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="car_name">Car Name</label>
                        <input type="text" name="car_name" id="car_name" value="<?php echo htmlspecialchars($car['car_name'] ?? ''); ?>" required>
                    </div>

                    <div class="form-group">
                        <label for="plate_number">Plate Number</label>
                        <input type="text" name="plate_number" id="plate_number" value="<?php echo htmlspecialchars($car['plate_number'] ?? ''); ?>" required>
                    </div>

                    <div class="form-group">
                        <label for="brand">Brand</label>
                        <input type="text" name="brand" id="brand" value="<?php echo htmlspecialchars($car['brand'] ?? ''); ?>">
                    </div>

                    <div class="form-group">
                        <label for="model">Model</label>
                        <input type="text" name="model" id="model" value="<?php echo htmlspecialchars($car['model'] ?? ''); ?>">
                    </div>

                    <div class="form-group">
                        <label for="year">Year</label>
                        <input type="number" name="year" id="year" value="<?php echo htmlspecialchars($car['year'] ?? ''); ?>">
                    </div>

                    <div class="form-group">
                        <label for="insurance_expiry">Insurance Expiry</label>
                        <input
                            type="text"
                            name="insurance_expiry"
                            id="insurance_expiry"
                            value="<?php echo htmlspecialchars($insurance_expiry_value); ?>"
                            placeholder="dd/mm/yyyy"
                        >
                        <div class="hint">Use Laos format: dd/mm/yyyy</div>
                    </div>

                    <div class="form-group">
                        <label for="service_due_date">Service Due Date</label>
                        <input
                            type="text"
                            name="service_due_date"
                            id="service_due_date"
                            value="<?php echo htmlspecialchars($service_due_date_value); ?>"
                            placeholder="dd/mm/yyyy"
                        >
                        <div class="hint">Use Laos format: dd/mm/yyyy</div>
                    </div>

                    <div class="form-group">
                        <label for="note">Note</label>
                        <textarea name="note" id="note"><?php echo htmlspecialchars($car['note'] ?? ''); ?></textarea>
                    </div>
                </div>

                <div class="page-actions">
                    <button type="submit" class="btn btn-primary">Update Car</button>
                    <a href="my_cars.php" class="btn btn-secondary">Back to My Cars</a>
                </div>
            </form>
        </div>
    </main>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    flatpickr("#insurance_expiry", {
        dateFormat: "d/m/Y",
        allowInput: true
    });

    flatpickr("#service_due_date", {
        dateFormat: "d/m/Y",
        allowInput: true
    });
});
</script>
</body>
</html>