<?php
/**
 * AI Concierge Controller
 * Handles guest queries via WhatsApp and auto-creates tickets
 */
class AIConciergeController {
    private $db;
    private $config;
    
    private $responses = [
        'wifi' => ['keywords' => ['wifi','wi-fi','internet','password','network','connect'],
            'action' => 'wifi_info'],
        'checkout' => ['keywords' => ['checkout','check out','check-out','leaving','departure'],
            'action' => 'checkout_info'],
        'checkin' => ['keywords' => ['checkin','check in','check-in','arrival','arrive'],
            'action' => 'checkin_info'],
        'breakfast' => ['keywords' => ['breakfast','morning meal','eat breakfast'],
            'action' => 'create_ticket', 'category' => 'food_beverage', 'type' => 'Order Breakfast'],
        'lunch' => ['keywords' => ['lunch','afternoon meal'],
            'action' => 'create_ticket', 'category' => 'food_beverage', 'type' => 'Order Lunch'],
        'dinner' => ['keywords' => ['dinner','evening meal','supper'],
            'action' => 'create_ticket', 'category' => 'food_beverage', 'type' => 'Order Dinner'],
        'room_service' => ['keywords' => ['room service','food','order food','hungry','meal'],
            'action' => 'create_ticket', 'category' => 'food_beverage', 'type' => 'Room Service'],
        'clean' => ['keywords' => ['clean','cleaning','tidy','housekeeping','maid'],
            'action' => 'create_ticket', 'category' => 'housekeeping', 'type' => 'Clean Room'],
        'towel' => ['keywords' => ['towel','towels','fresh towel'],
            'action' => 'create_ticket', 'category' => 'housekeeping', 'type' => 'Change Towels'],
        'ac' => ['keywords' => ['ac','air condition','cooling','cold','hot','temperature'],
            'action' => 'create_ticket', 'category' => 'maintenance', 'type' => 'AC Not Working'],
        'taxi' => ['keywords' => ['taxi','cab','ride','car','transport','uber'],
            'action' => 'create_ticket', 'category' => 'reception', 'type' => 'Taxi Request'],
        'airport' => ['keywords' => ['airport','flight','pickup','drop off','transfer'],
            'action' => 'create_ticket', 'category' => 'reception', 'type' => 'Airport Pickup'],
        'late_checkout' => ['keywords' => ['late checkout','extend stay','stay longer','extra hour'],
            'action' => 'create_ticket', 'category' => 'reception', 'type' => 'Late Checkout'],
        'maintenance' => ['keywords' => ['broken','fix','repair','not working','issue','problem','leak','plumbing'],
            'action' => 'create_ticket', 'category' => 'maintenance', 'type' => 'General Maintenance'],
    ];

    public function __construct($db, $config) {
        $this->db = $db;
        $this->config = $config;
    }

    public function handleQuery($data) {
        $message = strtolower(trim($data['message'] ?? ''));
        $sessionToken = $data['session_token'] ?? null;
        $phone = $data['phone'] ?? null;

        if (empty($message)) {
            return ['success' => false, 'message' => 'No message provided'];
        }

        // Get guest session
        $guest = null;
        if ($sessionToken) {
            $stmt = $this->db->prepare("SELECT * FROM whatsapp_sessions WHERE session_token=? AND status='active'");
            $stmt->execute([$sessionToken]);
            $guest = $stmt->fetch(PDO::FETCH_ASSOC);
        }

        // Match intent
        $matched = $this->matchIntent($message);

        if (!$matched) {
            return [
                'success' => true,
                'reply' => "I'd be happy to help! You can ask me about:\n\n"
                    . "- WiFi password\n- Checkout time\n- Room cleaning\n- Towels/pillows\n"
                    . "- Room service & meals\n- Taxi/airport pickup\n- Late checkout\n"
                    . "- Report a maintenance issue\n\nWhat would you like?",
                'action' => 'menu'
            ];
        }

        // Handle action
        if ($matched['action'] === 'wifi_info') {
            return $this->handleWifi($guest);
        } elseif ($matched['action'] === 'checkout_info') {
            return $this->handleCheckoutInfo($guest);
        } elseif ($matched['action'] === 'checkin_info') {
            return $this->handleCheckinInfo($guest);
        } elseif ($matched['action'] === 'create_ticket') {
            return $this->autoCreateTicket($guest, $matched, $message);
        }

        return ['success' => true, 'reply' => 'How can I help you?', 'action' => 'fallback'];
    }

    private function matchIntent($message) {
        foreach ($this->responses as $key => $config) {
            foreach ($config['keywords'] as $keyword) {
                if (strpos($message, $keyword) !== false) {
                    return $config;
                }
            }
        }
        return null;
    }

    private function handleWifi($guest) {
        $propertyId = $guest['property_id'] ?? 1;
        $stmt = $this->db->prepare("SELECT wifi_ssid, wifi_password FROM properties WHERE id=?");
        $stmt->execute([$propertyId]);
        $prop = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($prop && $prop['wifi_ssid']) {
            return [
                'success' => true,
                'reply' => "Here's your WiFi info:\n\nNetwork: {$prop['wifi_ssid']}\nPassword: {$prop['wifi_password']}\n\nEnjoy your stay!",
                'action' => 'wifi_info'
            ];
        }
        return ['success' => true, 'reply' => "Please check with the front desk for WiFi details.", 'action' => 'wifi_info'];
    }

    private function handleCheckoutInfo($guest) {
        $propertyId = $guest['property_id'] ?? 1;
        $stmt = $this->db->prepare("SELECT check_out_time FROM properties WHERE id=?");
        $stmt->execute([$propertyId]);
        $prop = $stmt->fetch(PDO::FETCH_ASSOC);
        $time = $prop['check_out_time'] ?? '11:00';
        $checkOut = $guest['check_out'] ?? 'your scheduled date';

        return [
            'success' => true,
            'reply' => "Checkout is at {$time}.\nYour checkout date: {$checkOut}\n\nNeed a late checkout? Just ask!",
            'action' => 'checkout_info'
        ];
    }

    private function handleCheckinInfo($guest) {
        $propertyId = $guest['property_id'] ?? 1;
        $stmt = $this->db->prepare("SELECT check_in_time FROM properties WHERE id=?");
        $stmt->execute([$propertyId]);
        $prop = $stmt->fetch(PDO::FETCH_ASSOC);
        $time = $prop['check_in_time'] ?? '14:00';

        return [
            'success' => true,
            'reply' => "Check-in starts at {$time}.\n\nNeed an early check-in? I can submit a request for you.",
            'action' => 'checkin_info'
        ];
    }

    private function autoCreateTicket($guest, $matched, $originalMessage) {
        require_once __DIR__ . '/service_tickets.php';
        $ticketCtrl = new ServiceTicketsController($this->db, $this->config);

        $result = $ticketCtrl->create([
            'property_id' => $guest['property_id'] ?? 1,
            'booking_id' => $guest['booking_id'] ?? null,
            'guest_id' => $guest['guest_id'] ?? null,
            'guest_name' => $guest['guest_name'] ?? 'Guest',
            'room_number' => $guest['room_number'] ?? null,
            'category' => $matched['category'],
            'request_type' => $matched['type'],
            'description' => $originalMessage
        ]);

        if ($result['success']) {
            $ticketNum = $result['ticket']['ticket_number'];
            return [
                'success' => true,
                'reply' => "Done! I've submitted your request.\n\nTicket: #{$ticketNum}\nRequest: {$matched['type']}\n\nOur team will be with you shortly!",
                'action' => 'ticket_created',
                'ticket' => $result['ticket']
            ];
        }

        return ['success' => false, 'reply' => 'Sorry, I could not submit your request. Please try again.'];
    }
}
