<?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');

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

// Validate input
if (empty($data['id']) || empty($data['name'])) {
    $returnArr = [
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Missing required fields!"
    ];
} else {
    $id = intval($data['id']);
    $owner_id = intval($input['owner_id']);
    $name = strip_tags(mysqli_real_escape_string($service, $data['name']));
    $lorry_id = intval($input['lorry_id']);
    
    $email = !empty($data['email']) ? strip_tags(mysqli_real_escape_string($service, $data['email'])) : null;
    $phone = !empty($data['phone']) ? strip_tags(mysqli_real_escape_string($service, $data['phone'])) : null;
    $ccode = mysqli_real_escape_string($service, $input['ccode']);
    // Check if sub-driver exists
    $checkUser = $service->query("SELECT * FROM sub_drivers WHERE id = $id");
    if ($checkUser->num_rows == 0) {
        $returnArr = [
            "ResponseCode" => "404",
            "Result" => "false",
            "ResponseMsg" => "Sub-driver not found!"
        ];
    } else {
        // 🔁 Email validation
        if (!empty($email)) {
            $emailCheck = $service->query("SELECT id FROM sub_drivers WHERE email = '$email' AND id != $id");
            if ($emailCheck->num_rows > 0) {
                echo json_encode([
                    "ResponseCode" => "409",
                    "Result" => "false",
                    "ResponseMsg" => "This email is already registered to another sub-driver!"
                ]);
                exit();
            }
        }

        // 🔁 Phone validation
        if (!empty($phone)) {
            $phoneCheck = $service->query("SELECT id FROM sub_drivers WHERE phone = '$phone' AND ccode='$ccode' AND id != $id");
            if ($phoneCheck->num_rows > 0) {
                echo json_encode([
                    "ResponseCode" => "409",
                    "Result" => "false",
                    "ResponseMsg" => "This phone number is already used by another sub-driver!"
                ]);
                exit();
            }
        }
        
        
        // 🔁 Lorry validation
        if (!empty($lorry_id)) {
            $phoneCheck = $service->query("SELECT id FROM sub_drivers WHERE lorry_id = '$lorry_id' AND id != $id");
            if ($phoneCheck->num_rows > 0) {
                echo json_encode([
                    "ResponseCode" => "409",
                    "Result" => "false",
                    "ResponseMsg" => "This lorry is already assigned to a sub-driver!"
                ]);
                exit();
            }
        }

        // 🚫 Demo mode check
        if ($owner_id == 3) {
            $returnArr = [
                "ResponseCode" => "200",
                "Result" => "false",
                "ResponseMsg" => "Demo mode: update is disabled."
            ];
        } else {
            $table = "sub_drivers";
            $fields = [
                'name' => $name
            ];
            if ($email) $fields['email'] = $email;
            if ($phone) $fields['phone'] = $phone;

            $where = "WHERE id = $id";

             $h = new FunctionQuery($service);
            $h->serviceupdateData_Api($fields, $table, $where);

            $updatedUser = $service->query("SELECT * FROM sub_drivers WHERE id = $id")->fetch_assoc();
            $returnArr = [
                "UserProfile" => $updatedUser,
                "ResponseCode" => "200",
                "Result" => "true",
                "ResponseMsg" => "Sub-driver profile updated successfully!"
            ];
        }
    }
}

echo json_encode($returnArr);
