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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request method";
    header('Location: all_customers.php');
    exit();
}

// Get form data
$customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone_number = trim($_POST['phone_number'] ?? '');
$address = trim($_POST['address'] ?? '');
$city = trim($_POST['city'] ?? '');
$postal_code = trim($_POST['postal_code'] ?? '');
$country = trim($_POST['country'] ?? '');
$status = isset($_POST['status']) ? intval($_POST['status']) : 1;

// Validate required fields
if ($customer_id <= 0 || empty($first_name)) {
    $_SESSION['error_message'] = "Customer ID and Company Name/First Name are required";
    header('Location: edit_customer.php?id=' . $customer_id);
    exit();
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Update customer record
    $sql = "UPDATE customers SET 
                first_name = ?, 
                last_name = ?, 
                email = ?,
                phone_number = ?, 
                address = ?, 
                city = ?, 
                postal_code = ?, 
                country = ?,
                status = ?
            WHERE customer_id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        'ssssssssii',
        $first_name,
        $last_name,
        $email,
        $phone_number,
        $address,
        $city,
        $postal_code,
        $country,
        $status,
        $customer_id
    );
    
    if (!$stmt->execute()) {
        throw new Exception("Error updating customer: " . $stmt->error);
    }
    
    // Commit transaction
    $conn->commit();
    
    // Success message
    $_SESSION['success_message'] = "Customer information updated successfully";
    header('Location: all_customers.php');
    exit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log the error
    error_log("Error updating customer: " . $e->getMessage());
    
    // Error message
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    header('Location: edit_customer.php?id=' . $customer_id);
    exit();
}
?>