<?php
header("Content-Type: application/json");
include '../../config.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

function debug_log($message) {
    error_log("[DEBUG] " . $message);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    debug_log("POST request received.");

    $id = isset($_POST['id']) ? intval($_POST['id']) : null;
    $firstname = $_POST['firstname'] ?? null;
    $middlename = $_POST['middlename'] ?? "";
    $lastname = $_POST['lastname'] ?? null;
    $phone = $_POST['phone'] ?? null;
    $nation_id = $_POST['nation_id'] ?? null;
    $country = $_POST['country'] ?? null;
    $region = $_POST['region'] ?? null;
    $street = $_POST['street'] ?? null;
    $ward = $_POST['ward'] ?? null;
    $gps = $_POST['gps'] ?? null;

    // debug_log("POST data: " . print_r($_POST, true));

    if (!$id || !$firstname || !$lastname || !$phone || !$nation_id || !$country || !$region || !$street || !$ward || !$gps) {
        debug_log("Missing required fields.");
        echo json_encode([
            'success' => false,
            'message' => 'Missing required fields.'
        ]);
        exit;
    }

    $imagePath = null;

    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        // debug_log("Image received for upload.");
        $uploadDir = '../../uploads/customers/';
        if (!is_dir($uploadDir)) {
            debug_log("Creating upload directory: $uploadDir");
            mkdir($uploadDir, 0777, true);
        }

        $fileTmpPath = $_FILES['image']['tmp_name'];
        $fileName = uniqid() . '_' . basename($_FILES['image']['name']);
        $destPath = $uploadDir . $fileName;

        // debug_log("Moving uploaded file to: $destPath");

        if (move_uploaded_file($fileTmpPath, $destPath)) {
            $imagePath = 'uploads/customers/' . $fileName;
            debug_log("Image uploaded successfully: $imagePath");
        } else {
            // debug_log("Image upload failed.");
            echo json_encode([
                'success' => false,
                'message' => 'Image upload failed.'
            ]);
            exit;
        }
    }

    if ($imagePath) {
        // debug_log("Updating customer with image.");
        $query = "UPDATE customers 
                  SET firstname = ?, middlename = ?, lastname = ?, phone = ?, nation_id = ?, country = ?, region = ?, street = ?, ward = ?, gps = ?, image = ?
                  WHERE id = ?";
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            debug_log("Prepare failed: " . $conn->error);
        }
        $stmt->bind_param("sssssssssssi", $firstname, $middlename, $lastname, $phone, $nation_id, $country, $region, $street, $ward, $gps, $imagePath, $id);

    } else {
        // debug_log("Updating customer without image.");
        $query = "UPDATE customers 
                  SET firstname = ?, middlename = ?, lastname = ?, phone = ?, nation_id = ?, country = ?, region = ?, street = ?, ward = ?, gps = ?
                  WHERE id = ?";
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            debug_log("Prepare failed: " . $conn->error);
        }
        $stmt->bind_param("ssssssssssi", $firstname, $middlename, $lastname, $phone, $nation_id, $country, $region, $street, $ward, $gps, $id);
    }

    if ($stmt->execute()) {
        // debug_log("Update executed successfully.");
        echo json_encode([
            'success' => true,
            'message' => 'Customer updated successfully.'
        ]);
    } else {
        // debug_log("Update failed: " . $stmt->error);
        echo json_encode([
            'success' => false,
            'message' => 'Failed to update customer.'
        ]);
    }

    $stmt->close();
} else {
    // debug_log("Invalid request method: " . $_SERVER['REQUEST_METHOD']);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method.'
    ]);
}
?>
