<?php

require_once 'databaseConnection.php';
$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);
}

// Only process if POST request
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (!isset($_GET['jobNumber'])) {  // Ensure jobNumber is provided
        echo "jobNumber is missing.";
        exit;
    } else {
        $jobNumber = $_GET['jobNumber']; // Get jobNumber from URL parameter
    }


    // -- Start updating the jobCard main data --
    $jobNumber = $_GET['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'];
    $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

    // Validate VIN Number (exactly 17 alphanumeric characters)
    if (!preg_match("/^[A-Za-z0-9]{17}$/", $vinNumber)) {
        die("Error: VIN Number must be exactly 17 characters long and contain only letters and numbers.");
    }


    // Capture other form data (same as your insert script)
    $stmt = $mysqli->prepare("UPDATE `jobCard` SET
        jobDate=?, registerNumber=?, year=?, millage=?, vehicleBrand=?, dateTimeIn=?, dateTimeOut=?,
        vehicleModel=?, vehicleColour=?, engineNumber=?, vinNumber=?, purpose=?,
        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=?
        WHERE jobNumber=?");

    $stmt->bind_param(
        "ssissssssssssssssssssdddddssdsdsddddis",
        $jobDate,
        $registerNumber,
        $year,
        $millage,
        $vehicleBrand,
        $dateTimeIn,
        $dateTimeOut,
        $vehicleModel,
        $vehicleColour,
        $engineNumber,
        $vinNumber,
        $purpose,
        $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,
         $jobNumber
    );
    $stmt->execute();
    $stmt->close();

    // ---- DELETE Old Main/Custom Data ----
    $deleteMain = $mysqli->prepare("DELETE FROM mainParts WHERE jobNumber = ?");
    $deleteMain->bind_param("s", $jobNumber);
    $deleteMain->execute();
    $deleteMain->close();

    $deleteCustom = $mysqli->prepare("DELETE FROM customs WHERE jobNumber = ?");
    $deleteCustom->bind_param("s", $jobNumber);
    $deleteCustom->execute();
    $deleteCustom->close();

    function insertMainData($mysqli, $jobID, $category, $types, $prices, $quantities, $discounts, $netAmounts)
    {
        $stmt = $mysqli->prepare("INSERT INTO mainParts (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();
        } else {
            die("Insert mainParts prepare failed: " . $mysqli->error);
        }
    }


    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();
        } else {
            die("Insert customs prepare failed: " . $mysqli->error);
        }
    }


    // Insert Main
    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'] ?? []);

    // Insert Custom
    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'] ?? []);

    // Done
    $mysqli->close();
    header("Location: ../product-list.php");
    exit;
} else {
    echo "Invalid access.";
}
