<?php
// admin/sync-customer.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$name = sanitize($_POST['name'] ?? '');
$phone = sanitize($_POST['phone'] ?? '');

if (empty($name) || empty($phone)) {
    echo json_encode(['success' => false, 'message' => 'Name and phone are required']);
    exit;
}

try {
    // Check if customer already exists
    $stmt = $pdo->prepare("SELECT id FROM customers WHERE phone = ?");
    $stmt->execute([$phone]);
    if ($stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'Customer already exists']);
        exit;
    }
    
    // Get customer data from orders
    $stmt = $pdo->prepare("SELECT name, phone, email, address, city 
                           FROM orders 
                           WHERE name = ? AND phone = ? 
                           LIMIT 1");
    $stmt->execute([$name, $phone]);
    $order = $stmt->fetch();
    
    if (!$order) {
        echo json_encode(['success' => false, 'message' => 'No orders found for this customer']);
        exit;
    }
    
    // Create customer
    $customer_code = 'CUS-' . date('Ymd') . '-' . rand(1000, 9999);
    $stmt = $pdo->prepare("INSERT INTO customers 
        (customer_code, name, email, phone, address, city) 
        VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $customer_code,
        $order['name'],
        $order['email'],
        $order['phone'],
        $order['address'],
        $order['city']
    ]);
    
    $customer_id = $pdo->lastInsertId();
    
    // Update orders with customer_id
    $stmt = $pdo->prepare("UPDATE orders SET customer_id = ? WHERE phone = ?");
    $stmt->execute([$customer_id, $phone]);
    
    echo json_encode(['success' => true, 'message' => 'Customer synced successfully']);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>