<?php
// Use absolute path to ensure database connection works from any context
$script_dir = dirname(__FILE__);
$root_dir = dirname($script_dir);

// Set error handling to prevent PHP errors from breaking JSON output
error_reporting(0);
ini_set('display_errors', 0);

try {
    include $root_dir . '/db.php';
    
    // Check if database connection is successful
    if (!$conn || $conn->connect_error) {
        throw new Exception('Database connection failed');
    }
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Database connection error: ' . $e->getMessage()]);
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'search') {
        // Real-time customer search by phone number
        $phone = trim($_POST['phone'] ?? '');
        
        if (empty($phone)) {
            echo json_encode(['success' => true, 'customers' => []]);
            exit;
        }
        
        // Search for customers whose phone number starts with the entered digits
        try {
            $stmt = $conn->prepare("SELECT id, name, email, address, phone FROM customers WHERE phone LIKE ? AND active = 1 ORDER BY name LIMIT 10");
            if (!$stmt) {
                throw new Exception('Failed to prepare search statement: ' . $conn->error);
            }
            
            $searchTerm = $phone . '%';
            $stmt->bind_param("s", $searchTerm);
            
            if (!$stmt->execute()) {
                throw new Exception('Failed to execute search: ' . $stmt->error);
            }
            
            $result = $stmt->get_result();
            
            $customers = [];
            while ($row = $result->fetch_assoc()) {
                $customers[] = $row;
            }
            
            echo json_encode([
                'success' => true, 
                'customers' => $customers,
                'count' => count($customers)
            ]);
            $stmt->close();
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Search error: ' . $e->getMessage()]);
        }
        
    } elseif ($action === 'create') {
        // Create new customer
        $name = trim($_POST['name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $address = trim($_POST['address'] ?? '');
        
        // Validate required fields
        if (empty($name) || empty($phone)) {
            echo json_encode(['success' => false, 'message' => 'Name and phone number are required']);
            exit;
        }
        
        // Check if phone number already exists
        try {
            $check_stmt = $conn->prepare("SELECT id FROM customers WHERE phone = ?");
            if (!$check_stmt) {
                throw new Exception('Failed to prepare check statement: ' . $conn->error);
            }
            
            $check_stmt->bind_param("s", $phone);
            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' => 'A customer with this phone number already exists']);
                $check_stmt->close();
                exit;
            }
            $check_stmt->close();
            
            // Insert new customer (delivery customers are not walk-in)
            $stmt = $conn->prepare("INSERT INTO customers (name, phone, email, address, is_walk_in, active, discount_applied, discount_rate, created_at) VALUES (?, ?, ?, ?, 0, 1, 'N', 0.00, NOW())");
            if (!$stmt) {
                throw new Exception('Failed to prepare insert statement: ' . $conn->error);
            }
            
            $stmt->bind_param("ssss", $name, $phone, $email, $address);
            
            if (!$stmt->execute()) {
                throw new Exception('Failed to execute insert: ' . $stmt->error);
            }
            
            $customer_id = $stmt->insert_id;
            echo json_encode([
                'success' => true, 
                'message' => 'Customer created successfully',
                'customer' => [
                    'id' => $customer_id,
                    'name' => $name,
                    'phone' => $phone,
                    'email' => $email,
                    'address' => $address
                ]
            ]);
            $stmt->close();
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error creating customer: ' . $e->getMessage()]);
        }
        
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?> 