<?php
session_start();
include '../db.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit;
}

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update') {
        // Update existing customer
        // Support both 'id' and 'customer_id' parameter names for backward compatibility
        $customer_id = intval($_POST['id'] ?? $_POST['customer_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $ntn = trim($_POST['ntn'] ?? '');
        $province = trim($_POST['province'] ?? '');
        $category_id = !empty($_POST['category_id']) ? intval($_POST['category_id']) : null;
        $is_walk_in = isset($_POST['is_walk_in']) ? 1 : 0;
        $active = isset($_POST['active']) ? 1 : 0;
        $discount_applied = isset($_POST['discount_applied']) ? 'Y' : 'N';
        $discount_rate = floatval($_POST['discount_rate'] ?? 0);
        
        // Validate required fields
        if (empty($customer_id) || empty($name) || empty($phone)) {
            echo json_encode(['success' => false, 'message' => 'Customer ID, name and phone number are required']);
            exit;
        }
        
        // Check if customer exists
        try {
            $check_stmt = $conn->prepare("SELECT id FROM customers WHERE id = ?");
            if (!$check_stmt) {
                throw new Exception('Failed to prepare check statement: ' . $conn->error);
            }
            
            $check_stmt->bind_param("i", $customer_id);
            if (!$check_stmt->execute()) {
                throw new Exception('Failed to execute check: ' . $check_stmt->error);
            }
            
            if ($check_stmt->get_result()->num_rows === 0) {
                echo json_encode(['success' => false, 'message' => 'Customer not found']);
                $check_stmt->close();
                exit;
            }
            $check_stmt->close();
            
            // Check if phone number already exists for another customer
            $phone_check_stmt = $conn->prepare("SELECT id FROM customers WHERE phone = ? AND id != ?");
            if (!$phone_check_stmt) {
                throw new Exception('Failed to prepare phone check statement: ' . $conn->error);
            }
            
            $phone_check_stmt->bind_param("si", $phone, $customer_id);
            if (!$phone_check_stmt->execute()) {
                throw new Exception('Failed to execute phone check: ' . $phone_check_stmt->error);
            }
            
            if ($phone_check_stmt->get_result()->num_rows > 0) {
                echo json_encode(['success' => false, 'message' => 'A customer with this phone number already exists']);
                $phone_check_stmt->close();
                exit;
            }
            $phone_check_stmt->close();
            
            // Update customer
            $stmt = $conn->prepare("UPDATE customers SET name = ?, phone = ?, email = ?, address = ?, ntn = ?, province = ?, category_id = ?, is_walk_in = ?, active = ?, discount_applied = ?, discount_rate = ? WHERE id = ?");
            if (!$stmt) {
                throw new Exception('Failed to prepare update statement: ' . $conn->error);
            }
            
            $stmt->bind_param("sssssssiisd", $name, $phone, $email, $address, $ntn, $province, $category_id, $is_walk_in, $active, $discount_applied, $discount_rate, $customer_id);
            
            if (!$stmt->execute()) {
                throw new Exception('Failed to execute update: ' . $stmt->error);
            }
            
            echo json_encode([
                'success' => true, 
                'message' => 'Customer updated successfully',
                'customer' => [
                    'id' => $customer_id,
                    'name' => $name,
                    'phone' => $phone,
                    'email' => $email,
                    'address' => $address,
                    'ntn' => $ntn,
                    'province' => $province,
                    'category_id' => $category_id,
                    'is_walk_in' => $is_walk_in,
                    'active' => $active
                ]
            ]);
            $stmt->close();
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error updating customer: ' . $e->getMessage()]);
        }
        
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
