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

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

/*
|--------------------------------------------------------------------------
| Workspace logic
|--------------------------------------------------------------------------
*/
$workspace_type = $_GET['workspace'] ?? $_POST['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';

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

$form = [
    'car_name' => '',
    'plate_number' => '',
    'brand' => '',
    'model' => '',
    'year' => '',
    'insurance_expiry' => '',
    'service_due_date' => '',
    'note' => ''
];

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

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

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

    $form['insurance_expiry'] = $insurance_expiry_raw;
    $form['service_due_date'] = $service_due_date_raw;

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

    if ($form['car_name'] === '' || $form['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";
    } elseif ($is_company_workspace && $active_company_id === null) {
        $message = "No active company selected.";
        $message_color = "red";
    } else {
        $stmt = $db->prepare("
            INSERT INTO cars (
                user_id,
                company_id,
                created_by,
                updated_by,
                car_name,
                plate_number,
                brand,
                model,
                year,
                insurance_expiry,
                service_due_date,
                note
            )
            VALUES (
                :user_id,
                :company_id,
                :created_by,
                :updated_by,
                :car_name,
                :plate_number,
                :brand,
                :model,
                :year,
                :insurance_expiry,
                :service_due_date,
                :note
            )
        ");

        // IMPORTANT: user_id must always be saved because your DB does not allow NULL
        $stmt->bindValue(":user_id", $user_id, PDO::PARAM_INT);

        if ($is_company_workspace) {
            $stmt->bindValue(":company_id", $active_company_id, PDO::PARAM_INT);
        } else {
            $stmt->bindValue(":company_id", null, PDO::PARAM_NULL);
        }

        $stmt->bindValue(":created_by", $user_id, PDO::PARAM_INT);
        $stmt->bindValue(":updated_by", $user_id, PDO::PARAM_INT);

        $stmt->bindValue(":car_name", $form['car_name'], PDO::PARAM_STR);
        $stmt->bindValue(":plate_number", $form['plate_number'], PDO::PARAM_STR);

        if ($form['brand'] !== '') {
            $stmt->bindValue(":brand", $form['brand'], PDO::PARAM_STR);
        } else {
            $stmt->bindValue(":brand", null, PDO::PARAM_NULL);
        }

        if ($form['model'] !== '') {
            $stmt->bindValue(":model", $form['model'], PDO::PARAM_STR);
        } else {
            $stmt->bindValue(":model", null, PDO::PARAM_NULL);
        }

        if ($form['year'] !== '') {
            $stmt->bindValue(":year", $form['year'], PDO::PARAM_STR);
        } else {
            $stmt->bindValue(":year", null, PDO::PARAM_NULL);
        }

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

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

        if ($form['note'] !== '') {
            $stmt->bindValue(":note", $form['note'], PDO::PARAM_STR);
        } else {
            $stmt->bindValue(":note", null, PDO::PARAM_NULL);
        }

        if ($stmt->execute()) {
            header("Location: my_cars.php?workspace=" . urlencode($scope) . "&scope=" . urlencode($scope));
            exit;
        } else {
            $message = "Failed to add car.";
            $message_color = "red";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add 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>Add Car</h1>
                    <p>Add a new car and track insurance and service dates.</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>

        <?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">Fill in the details below to create a new car record.</div>

            <form method="POST">
                <input type="hidden" name="workspace" value="<?php echo htmlspecialchars($scope); ?>">
                <input type="hidden" name="scope" value="<?php echo htmlspecialchars($scope); ?>">

                <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($form['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($form['plate_number']); ?>" required>
                    </div>

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

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

                    <div class="form-group">
                        <label for="year">Year</label>
                        <input type="number" name="year" id="year" value="<?php echo htmlspecialchars($form['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($form['insurance_expiry']); ?>"
                            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($form['service_due_date']); ?>"
                            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($form['note']); ?></textarea>
                    </div>
                </div>

                <div class="page-actions">
                    <button type="submit" class="btn btn-primary">Add Car</button>
                    <a href="my_cars.php?workspace=<?php echo htmlspecialchars($scope); ?>&scope=<?php echo htmlspecialchars($scope); ?>" 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>