<?php
require_once 'databaseConnection.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (
        !empty($_POST['jobNumber']) && !empty($_POST['jobDate']) && !empty($_POST['registerNumber']) &&
        !empty($_POST['year']) && !empty($_POST['millage']) && !empty($_POST['vehicleBrand']) &&
        !empty($_POST['vehicleModel']) && !empty($_POST['vehicleColour']) &&
        !empty($_POST['vinNumber']) && !empty($_POST['customerName']) && !empty($_POST['contactNumber']) &&
        !empty($_POST['jobCardStatus']) && isset($_POST['fuelBattery']) && isset($_POST['powerValue']) && isset($_POST['dateTimeIn'])
    ) {
        $mysqli = db_connect();
        if (!$mysqli) {
            echo "Database connection failed.";
            exit;
        }
        
        $job_number = $_POST['jobNumber'];
        
        $check_stmt = $mysqli->prepare("SELECT COUNT(*) FROM `customerField` WHERE `job_number` = ?");
        $check_stmt->bind_param("s", $job_number);
        $check_stmt->execute();
        $check_stmt->bind_result($count);
        $check_stmt->fetch();
        $check_stmt->close();
        
        if ($count > 0) {
            echo "<script>
                alert('Job number $job_number already exists. Please refresh the page for a new number.');
                window.history.back();
            </script>";
            exit;
        }
        
        $purposeAll = isset($_POST['purpose']) && is_array($_POST['purpose']) ? implode(", ", $_POST['purpose']) : null;
        $job_date = $_POST['jobDate'];
        $register_number = $_POST['registerNumber'];
        $year = (int)$_POST['year'];
        $millage = $_POST['millage'];
        $vehicle_brand = $_POST['vehicleBrand'];
        $vehicle_model = $_POST['vehicleModel'];
        $vehicle_colour = $_POST['vehicleColour'];
        $vin_number = $_POST['vinNumber'];
        $customer_name = $_POST['customerName'];
        $contact_number = $_POST['contactNumber'];
        $fuelBatteryType = ucfirst(strtolower(trim($_POST['fuelBattery'])));
        $powerValue = (int)$_POST['powerValue'];
        $dateTimeIn = $_POST['dateTimeIn'];
        $jobCardStatus = $_POST['jobCardStatus'];
        
        $customer_address = !empty($_POST['customerAddress']) ? $_POST['customerAddress'] : null;
        $reported_defects = !empty($_POST['reportedDefects']) ? $_POST['reportedDefects'] : null;
        $completed_action = !empty($_POST['completedAction']) ? $_POST['completedAction'] : null;
        $dateTimeOut = !empty($_POST['dateTimeOut']) ? $_POST['dateTimeOut'] : null;
        $engine_number = !empty($_POST['engineNumber']) ? $_POST['engineNumber'] : null;
        $contactPerson = !empty($_POST['contactPerson']) ? $_POST['contactPerson'] : null;
        $personContactNumber = !empty($_POST['personContactNumber']) ? $_POST['personContactNumber'] : null;
        $technicianName = !empty($_POST['technicianName']) ? $_POST['technicianName'] : null;
        $supervisor = !empty($_POST['supervisor']) ? $_POST['supervisor'] : null;
        $customerVAT = !empty($_POST['customerVAT']) ? $_POST['customerVAT'] : null;
        
        if (!in_array($fuelBatteryType, ['Fuel', 'Battery'])) {
            echo "Invalid fuel/battery type.";
            exit;
        }
        
        if (!preg_match("/^[A-Za-z0-9]{17}$/", $vin_number)) {
            die("Error: VIN Number must be exactly 17 characters long.");
        }
        
        $stmt = $mysqli->prepare("INSERT INTO `customerField`
        (`job_number`, `job_date`, `register_number`, `year`, `millage`, `vehicle_brand`, `dateTimeIn`, `dateTimeOut`, `vehicle_model`, `vehicle_colour`, `engine_number`, `vin_number`, `purposeAll`, `fuelBatteryType`, `powerValue`,
        `customer_name`, `customer_address`, `contact_number`, `reported_defects`, `completed_action`, `jobCardStatus`, `contactPerson`, `personContactNumber`, `technicianName`, `supervisor`, `imageOfCar`, `customerVAT`
        ) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        if (!$stmt) {
            echo "Error preparing statement: " . $mysqli->error;
            exit;
        }
        
        function uploadImage($file, $folder, $maxFileSize) {
            if ($file['size'] > $maxFileSize) {
                return null;
            }
            
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $fileType = finfo_file($finfo, $file["tmp_name"]);
            finfo_close($finfo);
            
            $fileExtension = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
            $allowedTypes = ['image/jpeg' => 'jpg', 'image/png' => 'png'];
            
            if (!isset($allowedTypes[$fileType]) || $allowedTypes[$fileType] !== $fileExtension) {
                return null;
            }
            
            $fileName = uniqid() . '_' . basename($file["name"]);
            $target_file = $folder . '/' . $fileName;
            
            if (move_uploaded_file($file["tmp_name"], $target_file)) {
                return substr($target_file, 3);
            }
            
            return null;
        }
        
        $image_folder = '../carDocuments/carImages';
        if (!file_exists($image_folder)) {
            mkdir($image_folder, 0755, true);
        }
        $maxFileSize = 4 * 1024 * 1024;
        
        $imageOfCar = !empty($_FILES["imageOfCar"]["name"]) ? uploadImage($_FILES["imageOfCar"], $image_folder, $maxFileSize) : null;
        
        $stmt->bind_param(
            "sssissssssssssisssssssssssi",
            $job_number,
            $job_date,
            $register_number,
            $year,
            $millage,
            $vehicle_brand,
            $dateTimeIn,
            $dateTimeOut,
            $vehicle_model,
            $vehicle_colour,
            $engine_number,
            $vin_number,
            $purposeAll,
            $fuelBatteryType,
            $powerValue,
            $customer_name,
            $customer_address,
            $contact_number,
            $reported_defects,
            $completed_action,
            $jobCardStatus,
            $contactPerson,
            $personContactNumber,
            $technicianName,
            $supervisor,
            $imageOfCar,
            $customerVAT
        );
        
        if ($stmt->execute()) {
            header("Location: ../customer.php");
            exit;
        } else {
            if ($stmt->errno == 1062) {
                echo "<script>
                    alert('Job number $job_number already exists. Please go back and refresh the page.');
                    window.history.back();
                </script>";
            } else {
                echo "Error inserting record: " . $stmt->error;
            }
        }
        
        $stmt->close();
        $mysqli->close();
    } else {
        echo "All required fields must be filled.";
    }
} else {
    echo "Invalid request method.";
}