<?php
header('Content-Type: application/json');

// Include the database connection file
// NOTE: Assuming getDbConnection() and sendErrorResponse() are defined in this file.
include 'db_connect.php'; 
$conn = getDbConnection();

// Helper function to send JSON error response and exit (assuming it's in db_connect.php or defined above)
if (!function_exists('sendErrorResponse')) {
    function sendErrorResponse($message, $code = 400) {
        http_response_code($code);
        echo json_encode(['success' => false, 'message' => $message]);
        exit();
    }
}

// 1. Check Request Method
if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
    sendErrorResponse("Invalid request method. PUT is required.", 405);
}

// 2. Read JSON Input
// For PUT requests, input must be read from php://input
$json_data = file_get_contents('php://input');
$data = json_decode($json_data, true);

if (empty($data)) {
    sendErrorResponse("No data provided or invalid JSON format.");
}

// 3. Extract and Validate Required Fields
// ⭐️ IMPORTANT: Use the camelCase names that the Android app sends (e.g., 'mobileNumber', not 'mobile_number')
$id = $data['id'] ?? null;
$name = $data['name'] ?? '';
$mobileNumber = $data['mobileNumber'] ?? ''; // Corrected to mobileNumber
$productLabel = $data['productLabel'] ?? ''; // Corrected to productLabel
$category = $data['category'] ?? '';
$note = $data['note'] ?? ''; // ⭐️ NEW FIELD ADDED

// ⭐️ Check all required fields including the new one
if (empty($id) || empty($name) || empty($mobileNumber) || empty($productLabel) || empty($category)) {
    sendErrorResponse("Missing required fields (id, name, mobileNumber, productLabel, category).");
}

// Simple ID and mobile number validation
if (!is_numeric($id) || $id <= 0) {
    sendErrorResponse("Invalid customer ID.");
}
// ⭐️ Use the camelCase variable for validation
if (!preg_match('/^\d{10,13}$/', $mobileNumber)) { 
    sendErrorResponse("Invalid mobile number format. Must be 10-13 digits.");
}


// 4. Prepare SQL Update Statement
// ⭐️ IMPORTANT: Update the SQL query to include the 'note' column!
// NOTE: I am assuming your DB columns are still snake_case (e.g., mobile_number, product_label).
$sql = "UPDATE customers SET 
        name=?, 
        mobile_number=?, 
        product_label=?, 
        category=?, 
        note=? 
        WHERE id=?";

$stmt = $conn->prepare($sql);

if ($stmt === false) {
    sendErrorResponse("SQL preparation failed: " . $conn->error, 500);
}

// Bind parameters: 's' for strings (5 strings), 'i' for integer ID (1 integer)
// ⭐️ IMPORTANT: Bind parameters now include the $note variable and one more 's'
$stmt->bind_param("sssssi", $name, $mobileNumber, $productLabel, $category, $note, $id);


// 5. Execute and Handle Results
try {
    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            // Success response
            echo json_encode([
                "success" => true, 
                "message" => "Customer ID **{$id}** updated successfully."
            ]);
        } else {
             // Handle case where ID exists but no data changed, or ID doesn't exist
             $check_sql = "SELECT id FROM customers WHERE id = ?";
             $check_stmt = $conn->prepare($check_sql);
             $check_stmt->bind_param("i", $id);
             $check_stmt->execute();
             if ($check_stmt->get_result()->num_rows === 0) {
                 sendErrorResponse("Customer ID **{$id}** not found.", 404); // Not Found
             } else {
                 // The record exists, but no fields were actually changed
                 echo json_encode([
                    "success" => true, 
                    "message" => "Customer ID **{$id}** updated successfully (or no changes detected)."
                 ]);
             }
             $check_stmt->close();
        }
    } else {
        // Handle unique key constraint error (for mobile_number)
        if ($conn->errno == 1062) {
            sendErrorResponse("Mobile number **{$mobileNumber}** already exists for another customer.", 409); // Conflict
        } else {
            sendErrorResponse("Database update failed: " . $stmt->error, 500);
        }
    }
} catch (Exception $e) {
    sendErrorResponse("An unexpected error occurred: " . $e->getMessage(), 500);
}

// 6. Close Connection
$stmt->close();
$conn->close();
?>