<?php
/**
 * Hostiva WhatsApp Admin Controller
 * Powers the WhatsApp dashboard: provider settings, message log, manual/test send, stats.
 */
require_once __DIR__ . '/../services/WhatsAppService.php';

class WhatsAppController {
    private $db;
    private $config;

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

    /* ---------- SETTINGS ---------- */
    public function getSettings($propertyId) {
        $propertyId = (int)($propertyId ?: 1);
        $stmt = $this->db->prepare("SELECT * FROM whatsapp_settings WHERE property_id = ? LIMIT 1");
        $stmt->execute([$propertyId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            // Never expose secrets to the client; just flag presence.
            $row['has_api_key']    = !empty($row['api_key']);
            $row['has_api_secret'] = !empty($row['api_secret']);
            unset($row['api_key'], $row['api_secret'], $row['webhook_secret']);
        }
        return ['success' => true, 'settings' => $row ?: ['property_id' => $propertyId, 'provider' => 'none', 'is_active' => 0]];
    }

    public function saveSettings($data) {
        $propertyId = (int)($data['property_id'] ?? 1);
        $provider   = in_array($data['provider'] ?? 'none', ['meta_cloud','twilio','none'], true) ? $data['provider'] : 'none';
        $isActive   = !empty($data['is_active']) ? 1 : 0;

        $stmt = $this->db->prepare("SELECT id, api_key, api_secret, webhook_secret FROM whatsapp_settings WHERE property_id = ? LIMIT 1");
        $stmt->execute([$propertyId]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        // Keep existing secrets if the client didn't send new ones (it never receives them).
        $apiKey        = ($data['api_key']        ?? '') !== '' ? $data['api_key']        : ($existing['api_key']        ?? null);
        $apiSecret     = ($data['api_secret']     ?? '') !== '' ? $data['api_secret']     : ($existing['api_secret']     ?? null);
        $webhookSecret = ($data['webhook_secret'] ?? '') !== '' ? $data['webhook_secret'] : ($existing['webhook_secret'] ?? bin2hex(random_bytes(16)));
        $phoneNumberId = $data['phone_number_id']   ?? null;
        $businessId    = $data['business_account_id'] ?? null;
        $webhookUrl    = $data['webhook_url']        ?? null;

        if ($existing) {
            $stmt = $this->db->prepare("
                UPDATE whatsapp_settings
                SET provider=?, api_key=?, api_secret=?, phone_number_id=?, business_account_id=?,
                    webhook_url=?, webhook_secret=?, is_active=?, updated_at=NOW()
                WHERE id=?
            ");
            $stmt->execute([$provider,$apiKey,$apiSecret,$phoneNumberId,$businessId,$webhookUrl,$webhookSecret,$isActive,$existing['id']]);
        } else {
            $stmt = $this->db->prepare("
                INSERT INTO whatsapp_settings
                    (property_id, provider, api_key, api_secret, phone_number_id, business_account_id,
                     webhook_url, webhook_secret, is_active)
                VALUES (?,?,?,?,?,?,?,?,?)
            ");
            $stmt->execute([$propertyId,$provider,$apiKey,$apiSecret,$phoneNumberId,$businessId,$webhookUrl,$webhookSecret,$isActive]);
        }

        return ['success' => true, 'message' => 'WhatsApp settings saved', 'webhook_verify_token' => $webhookSecret];
    }

    /* ---------- MESSAGE LOG ---------- */
    public function getMessages($q) {
        $where = [];
        $args  = [];
        if (!empty($q['direction']) && in_array($q['direction'], ['inbound','outbound'], true)) {
            $where[] = "direction = ?"; $args[] = $q['direction'];
        }
        if (!empty($q['phone'])) { $where[] = "recipient_phone LIKE ?"; $args[] = '%' . preg_replace('/[^0-9]/','',$q['phone']) . '%'; }
        if (!empty($q['status'])) { $where[] = "status = ?"; $args[] = $q['status']; }
        $sql = "SELECT id, direction, recipient_phone, recipient_name, message_type, message_body,
                       status, provider, related_ticket_id, related_booking_id, sent_at, created_at
                FROM whatsapp_messages";
        if ($where) $sql .= " WHERE " . implode(' AND ', $where);
        $sql .= " ORDER BY created_at DESC LIMIT 100";
        $stmt = $this->db->prepare($sql);
        $stmt->execute($args);
        return ['success' => true, 'messages' => $stmt->fetchAll(PDO::FETCH_ASSOC)];
    }

    /* ---------- MANUAL / TEST SEND ---------- */
    public function send($data) {
        $phone = preg_replace('/[^0-9+]/', '', $data['phone'] ?? '');
        $body  = trim($data['message'] ?? '');
        if ($phone === '' || $body === '') {
            return ['success' => false, 'message' => 'phone and message are required'];
        }
        $propertyId = (int)($data['property_id'] ?? 1);
        $wa = new WhatsAppService($this->db, $this->config, $propertyId);
        return $wa->sendMessage($phone, $data['name'] ?? null, $body, 'custom', [
            'booking_id' => $data['booking_id'] ?? null,
            'ticket_id'  => $data['ticket_id'] ?? null,
        ]);
    }

    /* ---------- STATS ---------- */
    public function getStats() {
        $row = $this->db->query("
            SELECT
              COUNT(*)                                             AS total,
              SUM(direction='outbound')                            AS outbound,
              SUM(direction='inbound')                             AS inbound,
              SUM(status='queued')                                 AS queued,
              SUM(status='sent' OR status='delivered' OR status='read') AS delivered,
              SUM(status='failed')                                 AS failed,
              SUM(created_at >= CURDATE())                         AS today
            FROM whatsapp_messages
        ")->fetch(PDO::FETCH_ASSOC);
        return ['success' => true, 'stats' => $row];
    }
}
