<?php
// modules/sales/ajax/save_customer.php
session_start();
require_once '../../assets/db_connect.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user'])) {
    echo json_encode(['status' => 'error', 'message' => 'Session expired']);
    exit;
}

$shop_id = $_SESSION['user']['shop_id'] ?? 0;
$name = $_POST['name'] ?? '';
$phone = $_POST['phone'] ?? '';
$email = $_POST['email'] ?? '';
$address = $_POST['address'] ?? '';

if (empty($name)) {
    echo json_encode(['status' => 'error', 'message' => 'Customer name is required']);
    exit;
}

try {
    // Check if customer with same phone exists
    if (!empty($phone)) {
        $check_sql = "SELECT id FROM customers WHERE phone = ? AND (shop_id = ? OR shop_id IS NULL)";
        $check_stmt = $pdo->prepare($check_sql);
        $check_stmt->execute([$phone, $shop_id]);
        if ($check_stmt->fetch()) {
            echo json_encode(['status' => 'error', 'message' => 'Customer with this phone already exists']);
            exit;
        }
    }
    
    // Insert new customer
    $sql = "INSERT INTO customers (shop_id, name, phone, email, address) 
            VALUES (?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$shop_id, $name, $phone, $email, $address]);
    
    $customer_id = $pdo->lastInsertId();
    
    // Get customer details
    $customer_sql = "SELECT * FROM customers WHERE id = ?";
    $customer_stmt = $pdo->prepare($customer_sql);
    $customer_stmt->execute([$customer_id]);
    $customer = $customer_stmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Customer saved successfully',
        'customer' => $customer
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to save customer: ' . $e->getMessage()
    ]);
}