<?php
require_once 'databaseConnection.php';

// Create a database connection
$mysqli = db_connect();
if (!$mysqli) {
    die("Database connection failed: " . mysqli_connect_error());
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Capture form data
    $jobNumber = $_POST['jobNumber'];
    $jobDate = $_POST['jobDate'];
    $registerNumber = $_POST['registerNumber'];
    $year = $_POST['year'];
    $dateTimeIn = $_POST['dateTimeIn'];
    $dateTimeOut = $_POST['dateTimeOut'];
    $millage = $_POST['millage'];
    $vehicleBrand = $_POST['vehicleBrand'];
    $vehicleModel = $_POST['vehicleModel'];
    $vehicleColour = $_POST['vehicleColour'];
    $engineNumber = $_POST['engineNumber'];
    $vinNumber = $_POST['vinNumber'];
    $fuelBatteryType = $_POST['fuelBatteryType'];
    $customerName = $_POST['customerName'];
    $contactNumber = $_POST['contactNumber'];
    $customerAddress = $_POST['customerAddress'];
    $purpose = $_POST['purpose'];
    $reportedDefects = $_POST['reportedDefects'];
    $completedAction = $_POST['completedAction'];

    if (!isset($_POST['jobNumber']) || empty($_POST['jobNumber'])) {
        die("Error: jobNumber is missing or empty.");
    }
    $jobNumber = $_POST['jobNumber']; // Assign it only if it's present
    

    // Create SQL query to insert the data into the jobs table
    $sql = "INSERT INTO jobData (job_number, job_date, register_number, year, date_time_in, date_time_out, millage, vehicle_brand, vehicle_model, vehicle_colour, engine_number, vin_number, fuel_battery_type, customer_name, contact_number, customer_address, purpose, reported_defects, completed_action)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

if ($stmt = $mysqli->prepare($sql)) {
    $stmt->bind_param("sssssssssssssssssss", $jobNumber, $jobDate, $registerNumber, $year, $dateTimeIn, $dateTimeOut, $millage, $vehicleBrand, $vehicleModel, $vehicleColour, $engineNumber, $vinNumber, $fuelBatteryType, $customerName, $contactNumber, $customerAddress, $purpose, $reportedDefects, $completedAction);

    if ($stmt->execute()) {
        echo "Job Data inserted successfully!<br>";
    } else {
        die("Error inserting jobData: " . $stmt->error);
    }
    $stmt->close();
} else {
    die("Error preparing jobData statement: " . $mysqli->error);
}


    // Insert into lubricants table
    $stmtLub = $mysqli->prepare("INSERT INTO lubricants (jobNumber, lubType, lubQuan, lubPrice, lubDis, lubNet, labourCode, labourQuan, labourPrice, labourDis, labourNet, dentType, dentQuan, dentPrice, dentDis, dentNet, spareType, spareQuan, sparePrice, spareDis, spareNet) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    if (!$stmtLub) {
        die("Error in preparing statement: " . $mysqli->error);
    }

    for ($i = 0; $i <= 10; $i++) {
        $lubType = $_POST["lubType" . ($i == 0 ? "" : $i)] ?? '';
        $lubQuan = $_POST["lubQuan" . ($i == 0 ? "" : $i)] ?? 0;
        $lubPrice = $_POST["lubPrice" . ($i == 0 ? "" : $i)] ?? 0;
        $lubDis = $_POST["lubDis" . ($i == 0 ? "" : $i)] ?? 0;
        $lubNet = $_POST["lubNet" . ($i == 0 ? "" : $i)] ?? 0;

        $labourCode = $_POST["labourCode" . ($i == 0 ? "" : $i)] ?? '';
        $labourQuan = $_POST["labourQuan" . ($i == 0 ? "" : $i)] ?? 0;
        $labourPrice = $_POST["labourPrice" . ($i == 0 ? "" : $i)] ?? 0;
        $labourDis = $_POST["labourDis" . ($i == 0 ? "" : $i)] ?? 0;
        $labourNet = $_POST["labourNet" . ($i == 0 ? "" : $i)] ?? 0;

        $dentType = $_POST["dentType" . ($i == 0 ? "" : $i)] ?? '';
        $dentQuan = $_POST["dentQuan" . ($i == 0 ? "" : $i)] ?? 0;
        $dentPrice = $_POST["dentPrice" . ($i == 0 ? "" : $i)] ?? 0;
        $dentDis = $_POST["dentDis" . ($i == 0 ? "" : $i)] ?? 0;
        $dentNet = $_POST["dentNet" . ($i == 0 ? "" : $i)] ?? 0;

        $spareType = $_POST["spareType" . ($i == 0 ? "" : $i)] ?? '';
        $spareQuan = $_POST["spareQuan" . ($i == 0 ? "" : $i)] ?? 0;
        $sparePrice = $_POST["sparePrice" . ($i == 0 ? "" : $i)] ?? 0;
        $spareDis = $_POST["spareDis" . ($i == 0 ? "" : $i)] ?? 0;
        $spareNet = $_POST["spareNet" . ($i == 0 ? "" : $i)] ?? 0;

        if (!empty(trim($lubType)) || !empty(trim($labourCode)) || !empty(trim($dentType)) || !empty(trim($spareType))) {
            $stmtLub->bind_param("ssidddsidddsidddsiddd", $jobNumber, $lubType, $lubQuan, $lubPrice, $lubDis, $lubNet, $labourCode, $labourQuan, $labourPrice, $labourDis, $labourNet, $dentType, $dentQuan, $dentPrice, $dentDis, $dentNet, $spareType, $spareQuan, $sparePrice, $spareDis, $spareNet);
            $stmtLub->execute();
        }
    }
    echo "Data inserted successfully!";
    $stmtLub->close();

    // Function to insert data into customs table
    function insertData($mysqli, $jobID, $category, $types, $prices, $discounts, $netAmounts)
    {
        $stmt = $mysqli->prepare("INSERT INTO customs (jobNumber, category, type_code, price, discount, net_amount) VALUES (?, ?, ?, ?, ?, ?)");
        if ($stmt) {
            foreach ($types as $index => $type) {
                if (!empty(trim($type))) {
                    $price = floatval($prices[$index] ?? 0);
                    $discount = floatval($discounts[$index] ?? 0);
                    $netAmount = floatval($netAmounts[$index] ?? 0);
                    $stmt->bind_param("ssssdd", $jobID, $category, $type, $price, $discount, $netAmount);
                    $stmt->execute();
                }
            }
            $stmt->close();
        }
    }

    // Insert custom data into different categories
    insertData($mysqli, $jobNumber, 'Lubricant', $_POST['customLubType'] ?? [], $_POST['customLubPrice'] ?? [], $_POST['customLubDis'] ?? [], $_POST['customLubNet'] ?? []);
    insertData($mysqli, $jobNumber, 'Labour', $_POST['customLabourCode'] ?? [], $_POST['customLabourPrice'] ?? [], $_POST['customLabourDis'] ?? [], $_POST['customLabourNet'] ?? []);
    insertData($mysqli, $jobNumber, 'Dent/Paint', $_POST['customDentType'] ?? [], $_POST['customDentPrice'] ?? [], $_POST['customDentDis'] ?? [], $_POST['customDentNet'] ?? []);
    insertData($mysqli, $jobNumber, 'Spare Parts', $_POST['customSpareType'] ?? [], $_POST['customSparePrice'] ?? [], $_POST['customSpareDis'] ?? [], $_POST['customSpareNet'] ?? []);

    echo "All data inserted successfully!";
    $mysqli->close();
} else {
    echo "Required fields are missing!";
}
