<?php

require_once 'databaseConnection.php';

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

function numberToWords($num)
{
    $ones = array(
        "",
        "One",
        "Two",
        "Three",
        "Four",
        "Five",
        "Six",
        "Seven",
        "Eight",
        "Nine",
        "Ten",
        "Eleven",
        "Twelve",
        "Thirteen",
        "Fourteen",
        "Fifteen",
        "Sixteen",
        "Seventeen",
        "Eighteen",
        "Nineteen"
    );
    $tens = array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety");

    if ($num == 0) return "Zero";

    $result = "";

    if ($num >= 10000000) {
        $result .= numberToWords(floor($num / 10000000)) . " Crore ";
        $num %= 10000000;
    }
    if ($num >= 100000) {
        $result .= numberToWords(floor($num / 100000)) . " Lakh ";
        $num %= 100000;
    }
    if ($num >= 1000) {
        $result .= numberToWords(floor($num / 1000)) . " Thousand ";
        $num %= 1000;
    }
    if ($num >= 100) {
        $result .= numberToWords(floor($num / 100)) . " Hundred ";
        $num %= 100;
    }
    if ($num > 0) {
        if ($num < 20) {
            $result .= $ones[$num];
        } else {
            $result .= $tens[floor($num / 10)];
            if ($num % 10 > 0) {
                $result .= " " . $ones[$num % 10];
            }
        }
    }

    return trim($result);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {


    // Collect POST data
    $jobNumber = $_POST['jobNumber'] ?? '';
    if (empty($jobNumber)) {
        die("Error: jobNumber is missing or empty.");
    }

    // Check if jobNumber already exists
    $checkStmt = $mysqli->prepare("SELECT COUNT(*) AS cnt FROM jobCard WHERE jobNumber = ?");
    $checkStmt->bind_param("s", $jobNumber);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    $countRow = $checkResult->fetch_assoc();
    if ($countRow['cnt'] > 0) {
        die("Error: jobNumber '" . htmlentities($jobNumber) . "' already exists. Please use a unique jobNumber.");
    }
    $checkStmt->close();
    // 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'];
    $fuelBatteryType = $_POST['fuelBatteryType'] ?? '';
    $engineNumber = $_POST['engineNumber'];
    $vinNumber = $_POST['vinNumber'];
    $customerName = $_POST['customerName'];
    $contactNumber = $_POST['contactNumber'];
    $customerAddress = $_POST['customerAddress'];
    $purpose = $_POST['purpose'];
    $reportedDefects = $_POST['reportedDefects'];
    $completedAction = $_POST['completedAction'];
    $contactPerson = $_POST['contactPerson'];
    $personContactNumber = $_POST['personContactNumber'];
    $technicianName = $_POST['technicianName'];
    $supervisor = $_POST['supervisor'];
    $TotalBillAmount = $_POST['TotalBillAmount'];
    $vatAmount = $_POST['vatAmount'];
    $discountAmount = $_POST['discountAmount'];
    $AmountOfDiscount = $_POST['AmountOfDiscount'];
    $netTotal = $_POST['netTotal'];
    $billNumber = $_POST['billNumber'];
    $billRemarks = $_POST['billRemarks'];
    $totalPaid = $_POST['totalPaid'];
    $totalPaidNumeric = floatval($netTotal);// no worry
    $totalPaidInWords = numberToWords($totalPaidNumeric) . " Only";
    $remainingAmount = $_POST['remainingAmount'];
    $paymentStatus = $_POST['paymentStatus'];
    $billAmount = $_POST['billAmount'];
    $lubricantBillAmount = $_POST['lubricantBillAmount'];
    $labourBillAmount = $_POST['labourBillAmount'];
    $dentBillAmount = $_POST['dentBillAmount'];
    $customerVAT = $_POST['customerVAT']; // Optional field

    // Prepared SQL statement for inserting job descriptions
    $stmt = $mysqli->prepare("INSERT INTO `jobCard`
        (`jobNumber`, `jobDate`, `registerNumber`, `year`, `millage`, `vehicleBrand`, `dateTimeIn`, `dateTimeOut`, `vehicleModel`, `vehicleColour`, `engineNumber`, `vinNumber`, `purpose`, `fuelBatteryType`,
        `customerName`, `customerAddress`, `contactNumber`, `reportedDefects`, `completedAction`, `contactPerson`, `personContactNumber`, `technicianName`, `supervisor`, `TotalBillAmount`, `vatAmount`, `discountAmount`, `AmountOfDiscount`, `netTotal`, `billNumber`, `billRemarks`, `totalPaid`, `totalPaidInWords`, `remainingAmount`, `paymentStatus`, `billAmount`, `lubricantBillAmount`, `labourBillAmount`, `dentBillAmount`, `customerVAT`
        ) 
    VALUES 
        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");




    if ($stmt === false) {
        echo json_encode(["status" => "error", "message" => "SQL preparation error: " . $mysqli->error]);
        exit;
    }



    $stmt->bind_param(
        "sssisssssssssssssssssssdddddssdsdsddddi",
        $jobNumber,
        $jobDate,
        $registerNumber,
        $year,
        $millage,
        $vehicleBrand,
        $dateTimeIn,
        $dateTimeOut,
        $vehicleModel,
        $vehicleColour,
        $engineNumber,
        $vinNumber,
        $purpose,
        $fuelBatteryType,
        $customerName,
        $customerAddress,
        $contactNumber,
        $reportedDefects,
        $completedAction,
        $contactPerson,
        $personContactNumber,
        $technicianName,
        $supervisor,
        $TotalBillAmount,
        $vatAmount,
        $discountAmount,
        $AmountOfDiscount,
        $netTotal,
        $billNumber,
        $billRemarks,
        $totalPaid,
        $totalPaidInWords,
        $remainingAmount,
        $paymentStatus,
        $billAmount,
        $lubricantBillAmount,
        $labourBillAmount,
        $dentBillAmount,
        $customerVAT
    );
    $stmt->execute();
    $stmt->close();

    // Function to insert data into customs table
    function insertMainData($mysqli, $jobID, $main_category, $main_types, $main_prices, $main_quantities, $main_discounts, $main_netAmounts)
    {
        $stmt = $mysqli->prepare(
            "INSERT INTO mainParts (jobNumber, category, type_code, price, quantity, discount, net_amount) 
        VALUES (?, ?, ?, ?, ?, ?, ?)"
        );
        if ($stmt) {
            foreach ($main_types as $index => $type) {
                if (!empty(trim($type))) {
                    $price = floatval($main_prices[$index] ?? 0);
                    $quantity = floatval($main_quantities[$index] ?? 1);
                    $discount = floatval($main_discounts[$index] ?? 0);
                    $netAmount = floatval($main_netAmounts[$index] ?? 0);
                    $stmt->bind_param("sssdddd", $jobID, $main_category, $type, $price, $quantity, $discount, $netAmount);
                    $stmt->execute();
                }
            }
            $stmt->close();
        }
    }


    // Insert main data into different categories
    insertMainData($mysqli, $jobNumber, 'Lubricant', $_POST['lubType'] ?? [], $_POST['lubPrice'] ?? [], $_POST['lubQuan'] ?? [], $_POST['lubDis'] ?? [], $_POST['lubNet'] ?? []);
    insertMainData($mysqli, $jobNumber, 'Labour', $_POST['labourCode'] ?? [], $_POST['labourPrice'] ?? [], $_POST['labourQuan'] ?? [], $_POST['labourDis'] ?? [], $_POST['labourNet'] ?? []);
    insertMainData($mysqli, $jobNumber, 'Dent/Paint', $_POST['dentType'] ?? [], $_POST['dentPrice'] ?? [], $_POST['dentQuan'] ?? [], $_POST['dentDis'] ?? [], $_POST['dentNet'] ?? []);
    insertMainData($mysqli, $jobNumber, 'Spare Parts', $_POST['spareType'] ?? [], $_POST['sparePrice'] ?? [], $_POST['spareQuan'] ?? [], $_POST['spareDis'] ?? [], $_POST['spareNet'] ?? []);

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


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

    // Close the connection before redirecting
    $mysqli->close();

    // Redirect after everything
    header("Location: ../product-list.php");
    exit;
} else {
    echo "Required fields are missing!";
}
