<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

// Debug: Log the POST data
error_log("Processing customer save request: " . print_r($_POST, true));

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    try {
        // Start transaction
        $conn->begin_transaction();
        
        // First insert the customer
        $stmt = $conn->prepare("INSERT INTO customers (
            first_name, 
            last_name, 
            email, 
            phone_number, 
            address,
            city,
            postal_code,
            country,
            status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)");
        
        // Prepare data
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $email = $_POST['email'] ?? null;
        $phone_number = $_POST['phone_number'] ?? null;
        $address = $_POST['street_address'] ?? null;
        $city = $_POST['city'] ?? null;
        $postal_code = $_POST['postal_code'] ?? null;
        $country = $_POST['country'] ?? null;
        
        error_log("Binding parameters for customer insert");
        $stmt->bind_param("ssssssss", 
            $first_name,
            $last_name,
            $email,
            $phone_number,
            $address,
            $city,
            $postal_code,
            $country
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Error executing customer insert: " . $stmt->error);
        }
        
        $customer_id = $conn->insert_id;
        error_log("New customer ID: " . $customer_id);
        
        // Commit the transaction
        $conn->commit();
        
        $_SESSION['success_message'] = "Customer added successfully";
        header("Location: customer_view.php?id=" . $customer_id);
        exit();
        
    } catch (Exception $e) {
        // An error occurred, rollback changes
        $conn->rollback();
        
        error_log("Error in save_customer_new.php: " . $e->getMessage());
        
        if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
            $_SESSION['error_message'] = "Email address already exists";
        } else {
            $_SESSION['error_message'] = "Error adding customer: " . $e->getMessage();
        }
        
        // Redirect back to form with error
        header("Location: add_customer.php");
        exit();
    }
} else {
    // Not a POST request
    $_SESSION['error_message'] = "Invalid request method";
    header("Location: add_customer.php");
    exit();
}
?>