<!-- Autors:Ervīns Jēkabsons; Mājas lapas daļa kur lietotājs (piereģistrēts) spēj reģistrēt automašīnas
Veidots 2024.gadā, jaunākā vesrija-->
<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "car_registration";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection error: " . $conn->connect_error);
}

// Handle car registration
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect form data
    $make = $_POST['make'];
    $model = $_POST['model'];
    $year = $_POST['year'];
    $color = $_POST['color'];
    $fuel = $_POST['fuel'];
    $price = $_POST['price'];
    $registration_number = $_POST['registration_number'];
    $vin = $_POST['vin'];
    $description = htmlspecialchars($_POST['description'], ENT_QUOTES);

    // Handle multiple photo uploads
    $photoPaths = [];
    if (isset($_FILES['photos']) && count($_FILES['photos']['name']) > 0) {
        $targetDir = "uploads/";
        foreach ($_FILES['photos']['name'] as $key => $fileName) {
            if ($_FILES['photos']['error'][$key] == UPLOAD_ERR_OK) {
                $targetFile = $targetDir . basename($fileName);
                if (move_uploaded_file($_FILES['photos']['tmp_name'][$key], $targetFile)) {
                    $photoPaths[] = $targetFile;
                }
            }
        }
    }

    // Encode photo paths as JSON
    $photosJson = json_encode($photoPaths);

    // Check for duplicate VIN
    $stmt = $conn->prepare("SELECT * FROM cars WHERE vin = ?");
    $stmt->bind_param("s", $vin);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        echo json_encode(["success" => false, "message" => "VIN already exists."]);
    } else {
        // Insert the new car record
        // Ensure you're binding the correct types for the query
        $insertQuery = "INSERT INTO cars (make, model, year, color, fuel, price, description, registration_number, vin, photo, owner_id) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($insertQuery);

        // Binding parameters with correct types:
        // s = string, i = integer, d = double
        $stmt->bind_param("sssssdssss", $make, $model, $year, $color, $fuel, $price, $description, $registration_number, $vin, $photosJson, $_SESSION['user_id']);

        if ($stmt->execute()) {
            echo json_encode(["success" => true, "message" => "Car successfully registered!"]);
        } else {
            echo json_encode(["success" => false, "message" => "Error: " . $stmt->error]);
        }
    }
    $stmt->close();
}
?>

<div class="admin-container">
    <header class="admin-header">
        <h2>Car Registration panel</h2>
        <div class="logout-container">
            <button onclick="window.location.href='logout.php'">Logout</button>
        </div>
    </header>
    <link rel="stylesheet" href="../css/styleadmin.css">
    <aside class="sidebar">
        <ul>
            <li><a href="index.php">Main</a></li>
            <li><a href="../html/about.html">About</a></li>
        </ul>
    </aside>

    <main class="main-content">
        <!-- Form for car registration -->
        <form id="carForm" method="POST" action="car_data.php" enctype="multipart/form-data">
            <script src="../javascript/script.js"></script>
            <script src="../javascript/vin.js"></script>

            <h3>Register a New Car</h3>

            <label for="make">Make:</label>
            <select id="make" name="make" required>
                <option value="">Select car brand:</option>
            </select>

            <label for="model">Model:</label>
            <input type="text" id="model" name="model" required>

            <label for="year">Year:</label>
            <input type="number" step="1" id="year" name="year">

            <label for="color">Color:</label>
            <select id="color" name="color" required>
                <option value="">Select car color:</option>
            </select>

            <label for="fuel">Fuel type:</label>
            <select id="fuel" name="fuel" required>
                <option value="">Fuel type:</option>
                <option value="Gasoline">Gasoline</option>
                <option value="Diesel">Diesel</option>
                <option value="Electric">Electric</option>
            </select>

            <label for="price">Price €:</label>
            <input type="text" id="price" name="price">

            <label for="registration_number">Registration Number:</label>
            <input type="text" id="registration_number" name="registration_number">

            <label for="vin">Chassis Nr./VIN:</label>
            <input type="text" id="vin" name="vin" maxlength="17" required>

            <label for="photos">Car Images:</label>
            <input type="file" id="photos" name="photos[]" accept="image/*" multiple required>

            <label for="description">Description:</label>
            <textarea id="description" name="description" rows="3"></textarea>

            <button type="submit">Submit</button>
        </form>
        <table>
            <thead>
            <tr>
                <th>ID</th>
                <th>Make</th>
                <th>Model</th>
                <th>Year</th>
                <th>Color</th>
                <th>Fuel</th>
                <th>Price €</th>
                <th>Photos</th>
                <th>Reg. No.</th>
                <th>VIN</th>
                <th>Description</th>
            </tr>
            </thead>
            <tbody>
            <?php
            $result = $conn->query("SELECT * FROM cars");
            while ($row = $result->fetch_assoc()) {
                echo "<tr>";
                echo "<td>" . $row['id'] . "</td>";
                echo "<td>" . $row['make'] . "</td>";
                echo "<td>" . $row['model'] . "</td>";
                echo "<td>" . $row['year'] . "</td>";
                echo "<td>" . $row['color'] . "</td>";
                echo "<td>" . $row['fuel'] . "</td>";
                echo "<td>" . $row['price'] . "</td>";

                $photos = json_decode($row['photo'], true); // Decode photo JSON
                if (is_array($photos) && !empty($photos)) {
                    echo "<td>";
                    foreach ($photos as $photo) {
                        echo "<img src='" . htmlspecialchars($photo, ENT_QUOTES) . "' style='width:80px; height:auto; margin-right:5px;'>";
                    }
                    echo "</td>";
                } else {
                    echo "<td>No images available</td>";
                }
                echo "<td>" . $row['registration_number'] . "</td>";
                echo "<td>" . $row['vin'] . "</td>";
                echo "<td>" . $row['description'] . "</td>";
                echo "</tr>";
            }
            ?>
            </tbody>
        </table>
    </main>
</div>
<?php $conn->close(); ?>
