<?php
/**
 * Table Customers API
 * Manages individual customers seated at tables
 */

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);

ob_start();

require 'config.php';

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

// Helper function to send JSON response (define early for use in auth checks)
function sendResponse($success, $message, $data) {
    ob_clean();
    http_response_code($success ? 200 : 400);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ]);
    exit;
}

// Check authentication based on role
$is_manager = isset($_SESSION['manager_id']);
$is_server = isset($_SESSION['server_id']);

if (!$is_manager && !$is_server) {
    http_response_code(401);
    sendResponse(false, 'Unauthorized access', null);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {
    case 'add':
        addCustomerToTable();
        break;
    case 'get_table_customers':
        getTableCustomers();
        break;
    case 'get_table_assignments':
        getTableAssignments();
        break;
    case 'update_status':
        updateCustomerStatus();
        break;
    case 'remove':
        removeCustomer();
        break;
    case 'get_assignment_customers':
        getAssignmentCustomers();
        break;
    default:
        sendResponse(false, 'Invalid action', null);
}

// Add a new customer to a table assignment
function addCustomerToTable() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(false, 'POST method required', null);
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    
    $required_fields = ['assignment_id', 'table_id'];
    foreach ($required_fields as $field) {
        if (!isset($data[$field])) {
            sendResponse(false, 'Missing required field: ' . $field, null);
        }
    }
    
    $assignment_id = intval($data['assignment_id']);
    $table_id = intval($data['table_id']);
    $customer_name = isset($data['customer_name']) ? $data['customer_name'] : 'Guest';
    $seat_number = isset($data['seat_number']) ? intval($data['seat_number']) : null;
    
    try {
        // Verify assignment exists and is active
        $verify_sql = "SELECT id FROM table_assignments 
                       WHERE id = ? AND table_id = ? AND status = 'assigned'";
        $stmt = $conn->prepare($verify_sql);
        $stmt->bind_param("ii", $assignment_id, $table_id);
        $stmt->execute();
        $verify_result = $stmt->get_result();
        
        if ($verify_result->num_rows === 0) {
            sendResponse(false, 'Invalid assignment or table', null);
            $stmt->close();
            return;
        }
        $stmt->close();
        
        // Insert customer
        $insert_sql = "INSERT INTO table_customers 
                       (assignment_id, table_id, customer_name, seat_number, status) 
                       VALUES (?, ?, ?, ?, 'seated')";
        $stmt = $conn->prepare($insert_sql);
        $stmt->bind_param("iisi", $assignment_id, $table_id, $customer_name, $seat_number);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to add customer: ' . $stmt->error);
        }
        
        $customer_id = $conn->insert_id;
        $stmt->close();
        
        sendResponse(true, 'Customer added successfully', [
            'customer_id' => $customer_id,
            'assignment_id' => $assignment_id,
            'customer_name' => $customer_name
        ]);
    } catch (Exception $e) {
        sendResponse(false, 'Error: ' . $e->getMessage(), null);
    }
}

// Get all customers for a table
function getTableCustomers() {
    global $conn;
    
    if (!isset($_GET['table_id'])) {
        sendResponse(false, 'Table ID is required', null);
    }
    
    $table_id = intval($_GET['table_id']);
    $assignment_id = isset($_GET['assignment_id']) ? intval($_GET['assignment_id']) : null;
    
    try {
        // Build query - simpler version without GROUP BY issues
        $sql = "SELECT tc.id, tc.assignment_id, tc.table_id, tc.customer_name, 
                       tc.seat_number, tc.status, tc.created_at
                FROM table_customers tc
                WHERE tc.table_id = ?";
        
        $params = [$table_id];
        $types = "i";
        
        if ($assignment_id) {
            $sql .= " AND tc.assignment_id = ?";
            $params[] = $assignment_id;
            $types .= "i";
        }
        
        $sql .= " ORDER BY tc.created_at ASC";
        
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $conn->error);
        }
        
        $stmt->bind_param($types, ...$params);
        if (!$stmt->execute()) {
            throw new Exception('Execute failed: ' . $stmt->error);
        }
        
        $result = $stmt->get_result();
        
        $customers = [];
        while ($row = $result->fetch_assoc()) {
            // Count orders separately
            $count_sql = "SELECT COUNT(*) as order_count FROM dine_in_orders WHERE customer_id = ?";
            $count_stmt = $conn->prepare($count_sql);
            $count_stmt->bind_param("i", $row['id']);
            $count_stmt->execute();
            $count_result = $count_stmt->get_result();
            $count_row = $count_result->fetch_assoc();
            $row['order_count'] = intval($count_row['order_count']);
            $count_stmt->close();
            
            $customers[] = $row;
        }
        $stmt->close();
        
        sendResponse(true, 'Customers fetched successfully', $customers);
    } catch (Exception $e) {
        sendResponse(false, 'Error: ' . $e->getMessage(), null);
    }
}

// Get customers for a specific assignment
function getAssignmentCustomers() {
    global $conn;
    
    if (!isset($_GET['assignment_id'])) {
        sendResponse(false, 'Assignment ID is required', null);
    }
    
    $assignment_id = intval($_GET['assignment_id']);
    
    try {
        $sql = "SELECT tc.id, tc.assignment_id, tc.table_id, tc.customer_name, 
                       tc.seat_number, tc.status, tc.created_at
                FROM table_customers tc
                WHERE tc.assignment_id = ?
                ORDER BY tc.created_at ASC";
        
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $conn->error);
        }
        
        $stmt->bind_param("i", $assignment_id);
        if (!$stmt->execute()) {
            throw new Exception('Execute failed: ' . $stmt->error);
        }
        
        $result = $stmt->get_result();
        
        $customers = [];
        while ($row = $result->fetch_assoc()) {
            // Count orders separately
            $count_sql = "SELECT COUNT(*) as order_count FROM dine_in_orders WHERE customer_id = ?";
            $count_stmt = $conn->prepare($count_sql);
            $count_stmt->bind_param("i", $row['id']);
            $count_stmt->execute();
            $count_result = $count_stmt->get_result();
            $count_row = $count_result->fetch_assoc();
            $row['order_count'] = intval($count_row['order_count']);
            $count_stmt->close();
            
            $customers[] = $row;
        }
        $stmt->close();
        
        sendResponse(true, 'Customers fetched successfully', $customers);
    } catch (Exception $e) {
        sendResponse(false, 'Error: ' . $e->getMessage(), null);
    }
}

// Update customer status
function updateCustomerStatus() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(false, 'POST method required', null);
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!isset($data['customer_id']) || !isset($data['status'])) {
        sendResponse(false, 'Customer ID and status are required', null);
    }
    
    $customer_id = intval($data['customer_id']);
    $status = $data['status'];
    
    // Validate status
    $valid_statuses = ['seated', 'served', 'departed'];
    if (!in_array($status, $valid_statuses)) {
        sendResponse(false, 'Invalid status', null);
    }
    
    try {
        $update_sql = "UPDATE table_customers SET status = ?, updated_at = NOW() WHERE id = ?";
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param("si", $status, $customer_id);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to update customer: ' . $stmt->error);
        }
        
        $stmt->close();
        
        sendResponse(true, 'Customer status updated successfully', [
            'customer_id' => $customer_id,
            'status' => $status
        ]);
    } catch (Exception $e) {
        sendResponse(false, 'Error: ' . $e->getMessage(), null);
    }
}

// Remove customer from table
function removeCustomer() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(false, 'POST method required', null);
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!isset($data['customer_id'])) {
        sendResponse(false, 'Customer ID is required', null);
    }
    
    $customer_id = intval($data['customer_id']);
    
    try {
        // Check if customer has pending orders
        $check_sql = "SELECT COUNT(*) as pending_count FROM dine_in_orders 
                      WHERE customer_id = ? AND status NOT IN ('completed', 'cancelled')";
        $stmt = $conn->prepare($check_sql);
        $stmt->bind_param("i", $customer_id);
        $stmt->execute();
        $check_result = $stmt->get_result();
        $pending = $check_result->fetch_assoc();
        $stmt->close();
        
        if ($pending['pending_count'] > 0) {
            sendResponse(false, 'Cannot remove customer with pending orders', null);
            return;
        }
        
        // Mark customer as departed instead of deleting
        $update_sql = "UPDATE table_customers SET status = 'departed', updated_at = NOW() WHERE id = ?";
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param("i", $customer_id);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to remove customer: ' . $stmt->error);
        }
        
        $stmt->close();
        
        sendResponse(true, 'Customer removed successfully', [
            'customer_id' => $customer_id
        ]);
    } catch (Exception $e) {
        sendResponse(false, 'Error: ' . $e->getMessage(), null);
    }
}

// Get all assignments for a table (grouped batches)
function getTableAssignments() {
    global $conn;
    
    if (!isset($_GET['table_id'])) {
        sendResponse(false, 'Table ID is required', null);
    }
    
    $table_id = intval($_GET['table_id']);
    
    try {
        $sql = "SELECT id, table_id, server_id, number_of_guests, assigned_at, status
                FROM table_assignments 
                WHERE table_id = ? AND status = 'assigned'
                ORDER BY assigned_at ASC";
        
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $conn->error);
        }
        
        if (!$stmt->bind_param("i", $table_id)) {
            throw new Exception('Bind failed: ' . $stmt->error);
        }
        
        if (!$stmt->execute()) {
            throw new Exception('Execute failed: ' . $stmt->error);
        }
        
        $result = $stmt->get_result();
        
        $assignments = [];
        while ($row = $result->fetch_assoc()) {
            $assignments[] = [
                'id' => intval($row['id']),
                'table_id' => intval($row['table_id']),
                'server_id' => intval($row['server_id']),
                'number_of_guests' => intval($row['number_of_guests']),
                'assigned_at' => $row['assigned_at'],
                'status' => $row['status']
            ];
        }
        $stmt->close();
        
        sendResponse(true, 'Assignments retrieved successfully', $assignments);
    } catch (Exception $e) {
        sendResponse(false, 'Error: ' . $e->getMessage(), null);
    }
}
?>

