<?php
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
include 'layouts/dbconn.php';

// Log the incoming request
//error_log("Received POST request: " . print_r($_POST, true));

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $response = ['success' => false, 'message' => ''];
    
    try {
        // Get the customer data
        $firstName = $_POST['first_name'] ?? null;
        $lastName = $_POST['last_name'] ?? null;
        $email = $_POST['email'] ?? null;
        $phoneNumber = $_POST['phone_number'] ?? null;
        $address = $_POST['address'] ?? null;
        $city = $_POST['city'] ?? null;
        $country = $_POST['country'] ?? 'KE';
        
        // Validate required fields
        if (!$firstName || !$lastName || !$email) {
            throw new Exception("Required fields are missing");
        }

        // Log the data being processed
        //error_log("Processing customer data: " . json_encode([
        //    'firstName' => $firstName,
        //    'lastName' => $lastName,
        //    'email' => $email
        //])
        //);
        
        // Start transaction
        $conn->begin_transaction();
        
        // Insert into customers table
        $customerStmt = $conn->prepare("INSERT INTO customers (user_id, first_name, last_name, email, phone_number, address, city, country) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $userId = 1;
        $customerStmt->bind_param("isssssss", $userId, $firstName, $lastName, $email, $phoneNumber, $address, $city, $country);
        
        if (!$customerStmt->execute()) {
            throw new Exception("Error inserting customer: " . $customerStmt->error);
        }
        
        $customerId = $customerStmt->insert_id;
        //error_log("Customer inserted with ID: " . $customerId);
        
        $customerStmt->close();
        
        // First, update all existing addresses for this customer to not be default
        $updateStmt = $conn->prepare("UPDATE customer_addresses SET is_default = 0 WHERE customer_id = ?");
        $updateStmt->bind_param("i", $customerId);
        
        if (!$updateStmt->execute()) {
            throw new Exception("Error updating existing addresses: " . $updateStmt->error);
        }
        
        $updateStmt->close();
        
        // Then insert the new address
        $addressStmt = $conn->prepare("INSERT INTO customer_addresses (customer_id, address_type, street_address, city, state, postal_code, country, is_default) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        
        $addressType = $_POST['address_type'] ?? 'home';
        $streetAddress = $_POST['address'] ?? '';
        $state = $_POST['state'] ?? '';
        $postalCode = $_POST['postal_code'] ?? '';
        $isDefault = 1;
        
        $addressStmt->bind_param("issssssi", $customerId, $addressType, $streetAddress, $city, $state, $postalCode, $country, $isDefault);
        
        if (!$addressStmt->execute()) {
            throw new Exception("Error inserting address: " . $addressStmt->error);
        }
        
        $addressId = $addressStmt->insert_id;
        //error_log("Address inserted with ID: " . $addressId);
        
        $addressStmt->close();
        
        // Commit transaction
        $conn->commit();
        
        // Return success response
        $response = [
            'success' => true,
            'customer_id' => $customerId,
            'first_name' => $firstName,
            'last_name' => $lastName,
            'address_id' => $addressId
        ];
        
    } catch (Exception $e) {
        //error_log("Error in save_customer_mod.php: " . $e->getMessage());
        // Rollback transaction on error
        if (isset($conn) && $conn->ping()) {
            $conn->rollback();
        }
        $response = [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }
    
    // Close connection
    if (isset($conn)) {
        $conn->close();
    }
    
    // Send JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// Log if we somehow got here without POST
error_log("Request method was not POST: " . $_SERVER["REQUEST_METHOD"]);
?>