<?php 
require dirname( dirname(__FILE__) ).'/inc/config.php';
require dirname( dirname(__FILE__) ).'/inc/FunctionQuery.php';
require dirname( dirname(__FILE__) ).'/inc/keyvaliation.php';
header('Content-type: application/json');

// Read JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Validate input
if (
    empty($input['owner_id']) || empty($input['lorry_id']) || 
    empty($input['name']) || empty($input['email']) || 
    empty($input['password']) || empty($input['phone']) || 
    empty($input['ccode'])
) {
    $returnArr = [
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Missing required fields!"
    ];
} else {
    $owner_id = intval($input['owner_id']);
    $lorry_id = intval($input['lorry_id']);
    $name = mysqli_real_escape_string($service, $input['name']);
    $email = mysqli_real_escape_string($service, $input['email']);
    $password = mysqli_real_escape_string($service, $input['password']);
    $phone = mysqli_real_escape_string($service, $input['phone']);
    $ccode = mysqli_real_escape_string($service, $input['ccode']);

    // 1️⃣ Check if email already exists
    $check_email = mysqli_query($service, "SELECT id FROM sub_drivers WHERE email='$email'");
    if (mysqli_num_rows($check_email) > 0) {
        $returnArr = [
            "ResponseCode" => "409",
            "Result" => "false",
            "ResponseMsg" => "Email already exists!"
        ];
    }
    // 2️⃣ Check if phone is already used
    elseif (mysqli_num_rows(mysqli_query($service, "SELECT id FROM sub_drivers WHERE phone='$phone' and ccode='$ccode'")) > 0) {
        $returnArr = [
            "ResponseCode" => "409",
            "Result" => "false",
            "ResponseMsg" => "Phone number already used by another sub-driver!"
        ];
    }
    // 3️⃣ Check if lorry is already assigned
    elseif (mysqli_num_rows(mysqli_query($service, "SELECT id FROM sub_drivers WHERE lorry_id='$lorry_id'")) > 0) {
        $returnArr = [
            "ResponseCode" => "409",
            "Result" => "false",
            "ResponseMsg" => "This lorry is already assigned to a sub-driver!"
        ];
    }
    // 4️⃣ Check if owner_id exists in tbl_lowner
    elseif (mysqli_num_rows(mysqli_query($service, "SELECT id FROM tbl_lowner WHERE id='$owner_id'")) == 0) {
        $returnArr = [
            "ResponseCode" => "404",
            "Result" => "false",
            "ResponseMsg" => "Owner not found!"
        ];
    }
    // 5️⃣ Check if lorry_id exists in tbl_lorry
    elseif (mysqli_num_rows(mysqli_query($service, "SELECT id FROM tbl_lorry WHERE id='$lorry_id'")) == 0) {
        $returnArr = [
            "ResponseCode" => "404",
            "Result" => "false",
            "ResponseMsg" => "Lorry not found!"
        ];
    }
    // 6️⃣ Check if the lorry is assigned to the owner
    elseif (mysqli_num_rows(mysqli_query($service, "SELECT id FROM tbl_lorry WHERE id='$lorry_id' AND owner_id='$owner_id'")) == 0) {
        $returnArr = [
            "ResponseCode" => "403",
            "Result" => "false",
            "ResponseMsg" => "This lorry does not belong to the specified owner!"
        ];
    }
    else {
        $table = "sub_drivers";
        $field_values = ["owner_id", "lorry_id", "name", "email", "password", "phone", "ccode"];
        $data_values = [$owner_id, $lorry_id, $name, $email, $password, $phone, $ccode];

        if ($owner_id == 3) {
            $returnArr = [
                "ResponseCode" => "200",
                "Result" => "false",
                "ResponseMsg" => "Demo mode: insert/update/delete is disabled. Create your own account to enable."
            ];
        } else {
             $h = new FunctionQuery($service);
            $insert = $h->serviceinsertdata_Api_Id($field_values, $data_values, $table);

            $returnArr = [
                "sub_driver_id" =>$insert,
                "ResponseCode" => "200",
                "Result" => "true",
                "ResponseMsg" => "Sub-driver added successfully!"
            ];
        }
    }
}

echo json_encode($returnArr);
