<?php
/**
 * Hostiva WhatsApp Service
 * Provider-agnostic WhatsApp messaging with Meta Cloud + Twilio support
 */
class WhatsAppService {
    private $db;
    private $config;
    private $provider;
    private $settings;

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

    private function loadSettings($propertyId) {
        $stmt = $this->db->prepare("SELECT * FROM whatsapp_settings WHERE property_id = ? AND is_active = 1 LIMIT 1");
        $stmt->execute([$propertyId]);
        $this->settings = $stmt->fetch(PDO::FETCH_ASSOC);
        $this->provider = $this->settings['provider'] ?? 'none';
    }

    // ===== SEND MESSAGE (PROVIDER AGNOSTIC) =====
    public function sendMessage($phone, $name, $messageBody, $type, $meta = []) {
        // Log the message
        $msgId = $this->logMessage($phone, $name, $messageBody, $type, $meta);

        if ($this->provider === 'none' || !$this->settings) {
            // Queue only — no active provider
            return ['success' => true, 'queued' => true, 'message_id' => $msgId];
        }

        try {
            if ($this->provider === 'meta_cloud') {
                $result = $this->sendViaMeta($phone, $messageBody);
            } elseif ($this->provider === 'twilio') {
                $result = $this->sendViaTwilio($phone, $messageBody);
            } else {
                return ['success' => false, 'error' => 'Unknown provider'];
            }

            // Update status
            $stmt = $this->db->prepare("UPDATE whatsapp_messages SET status='sent', sent_at=NOW(), provider_message_id=? WHERE id=?");
            $stmt->execute([$result['provider_id'] ?? null, $msgId]);

            return ['success' => true, 'sent' => true, 'message_id' => $msgId];
        } catch (Exception $e) {
            $stmt = $this->db->prepare("UPDATE whatsapp_messages SET status='failed', error_message=? WHERE id=?");
            $stmt->execute([$e->getMessage(), $msgId]);
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    private function sendViaMeta($phone, $body) {
        $url = "https://graph.facebook.com/v18.0/{$this->settings['phone_number_id']}/messages";
        $data = [
            'messaging_product' => 'whatsapp',
            'to' => $phone,
            'type' => 'text',
            'text' => ['body' => $body]
        ];
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $this->settings['api_key']
            ],
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_RETURNTRANSFER => true
        ]);
        $response = json_decode(curl_exec($ch), true);
        curl_close($ch);
        return ['provider_id' => $response['messages'][0]['id'] ?? null];
    }

    private function sendViaTwilio($phone, $body) {
        $sid = $this->settings['api_key'];
        $token = $this->settings['api_secret'];
        $from = 'whatsapp:+' . $this->settings['phone_number_id'];
        $to = 'whatsapp:+' . ltrim($phone, '+');

        $url = "https://api.twilio.com/2010-04-01/Accounts/{$sid}/Messages.json";
        $data = ['From' => $from, 'To' => $to, 'Body' => $body];

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_USERPWD => "$sid:$token",
            CURLOPT_POSTFIELDS => http_build_query($data),
            CURLOPT_RETURNTRANSFER => true
        ]);
        $response = json_decode(curl_exec($ch), true);
        curl_close($ch);
        return ['provider_id' => $response['sid'] ?? null];
    }

    private function logMessage($phone, $name, $body, $type, $meta = []) {
        $stmt = $this->db->prepare("
            INSERT INTO whatsapp_messages (direction, recipient_phone, recipient_name, message_type, message_body, 
                related_ticket_id, related_booking_id, provider, status)
            VALUES ('outbound', ?, ?, ?, ?, ?, ?, ?, 'queued')
        ");
        $stmt->execute([
            $phone, $name, $type, $body,
            $meta['ticket_id'] ?? null, $meta['booking_id'] ?? null,
            $this->provider ?? 'none'
        ]);
        return $this->db->lastInsertId();
    }

    // ===== MESSAGE TEMPLATES =====
    public function sendWelcome($guestName, $phone, $propertyName, $checkIn, $checkOut, $room, $portalLink, $bookingId) {
        $msg = "🏨 Welcome to {$propertyName}!\n\n"
             . "Your booking is confirmed.\n\n"
             . "📅 Check-in: {$checkIn}\n"
             . "📅 Check-out: {$checkOut}\n"
             . "🚪 Room: {$room}\n\n"
             . "🔗 Your Guest Portal:\n{$portalLink}\n\n"
             . "Need anything? Just message us here!";
        return $this->sendMessage($phone, $guestName, $msg, 'welcome', ['booking_id' => $bookingId]);
    }

    public function sendTicketCreated($staffPhone, $staffName, $ticket) {
        $msg = "🔔 NEW TASK\n\n"
             . "Guest: {$ticket['guest_name']}\n"
             . "Room: {$ticket['room_number']}\n\n"
             . "Request: {$ticket['request_type']}\n"
             . "{$ticket['description']}\n\n"
             . "Priority: " . strtoupper($ticket['priority']) . "\n"
             . "Ticket: #{$ticket['ticket_number']}\n\n"
             . "Please update status when started.";
        return $this->sendMessage($staffPhone, $staffName, $msg, 'ticket_created', ['ticket_id' => $ticket['id']]);
    }

    public function sendTicketUpdate($phone, $name, $ticketNumber, $newStatus, $updatedBy) {
        $statusEmoji = ['assigned'=>'👤','in_progress'=>'🔧','completed'=>'✅','verified'=>'⭐'];
        $emoji = $statusEmoji[$newStatus] ?? '📋';
        $msg = "{$emoji} Ticket #{$ticketNumber}\n\nStatus: " . ucwords(str_replace('_',' ',$newStatus)) . "\nUpdated by: {$updatedBy}";
        return $this->sendMessage($phone, $name, $msg, 'ticket_update');
    }

    public function sendReminder($staffPhone, $staffName, $ticket, $minutesElapsed) {
        $msg = "⏰ REMINDER\n\nTicket #{$ticket['ticket_number']} is still {$ticket['status']}.\n\n"
             . "Guest: {$ticket['guest_name']}\nRoom: {$ticket['room_number']}\n"
             . "Request: {$ticket['request_type']}\n\n"
             . "Time elapsed: {$minutesElapsed} minutes\n\nPlease update immediately.";
        return $this->sendMessage($staffPhone, $staffName, $msg, 'reminder', ['ticket_id' => $ticket['id']]);
    }

    public function sendCheckout($guestPhone, $guestName, $propertyName, $reviewLink) {
        $msg = "🙏 Thank you for staying at {$propertyName}!\n\n"
             . "We hope you had a wonderful experience.\n\n"
             . "📝 Please leave a review:\n{$reviewLink}\n\n"
             . "We look forward to hosting you again!";
        return $this->sendMessage($guestPhone, $guestName, $msg, 'checkout');
    }

    public function sendDutySchedule($staffPhone, $staffName, $assignments) {
        $msg = "📋 TODAY'S ASSIGNMENTS\n\n";
        foreach ($assignments as $i => $a) {
            $msg .= ($i+1) . ". Room {$a['room_number']} — {$a['assignment_type']}\n";
        }
        $msg .= "\nTotal: " . count($assignments) . " tasks\n\n✅ Confirm start of shift.";
        return $this->sendMessage($staffPhone, $staffName, $msg, 'duty_schedule');
    }

    public function sendOwnerSummary($ownerPhone, $ownerName, $propertyName, $stats) {
        $msg = "📊 DAILY SUMMARY — {$propertyName}\n\n"
             . "🏠 Occupancy: {$stats['occupancy']}%\n"
             . "💰 Revenue Today: \${$stats['revenue']}\n"
             . "➡️ Check-ins: {$stats['checkins']}\n"
             . "⬅️ Check-outs: {$stats['checkouts']}\n"
             . "📋 Pending Tasks: {$stats['pending_tasks']}\n"
             . "⭐ Guest Satisfaction: {$stats['satisfaction']}/5";
        return $this->sendMessage($ownerPhone, $ownerName, $msg, 'daily_summary');
    }

    // ===== GUEST SESSION MANAGEMENT =====
    public function createGuestSession($guestId, $bookingId, $propertyId, $phone, $name, $room, $checkIn, $checkOut) {
        $token = bin2hex(random_bytes(32));
        $stmt = $this->db->prepare("
            INSERT INTO whatsapp_sessions (guest_id, booking_id, property_id, phone, guest_name, room_number, check_in, check_out, session_token)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$guestId, $bookingId, $propertyId, $phone, $name, $room, $checkIn, $checkOut, $token]);
        return $token;
    }

    public function closeGuestSession($bookingId) {
        $stmt = $this->db->prepare("UPDATE whatsapp_sessions SET status='closed', closed_at=NOW() WHERE booking_id=? AND status='active'");
        $stmt->execute([$bookingId]);
    }
}
