<?php
require_once __DIR__ . '/../../../../helpers/response.php';
require_once __DIR__ . '/../../../../helpers/validation.php';
require_once __DIR__ . '/../../../Middleware/AuthMiddleware.php';
require_once __DIR__ . '/../../../Models/Database.php';

class ChatController {
    
    public function rooms() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();

        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $limit = isset($_GET['limit']) ? max(1, intval($_GET['limit'])) : 10;
        $offset = ($page - 1) * $limit;

        $totalStmt = $db->prepare("SELECT COUNT(*) FROM chat_references WHERE customer_id = ?");
        $totalStmt->execute([$customerId]);
        $total = (int) $totalStmt->fetchColumn();

        $stmt = $db->prepare("
            SELECT cr.*, v.agency_name as vendor_name, v.logo as vendor_logo, m.full_name as maid_name
            FROM chat_references cr
            JOIN vendors v ON cr.vendor_id = v.id
            LEFT JOIN maids m ON cr.maid_id = m.id
            WHERE cr.customer_id = ?
            ORDER BY cr.created_at DESC
            LIMIT " . intval($limit) . " OFFSET " . intval($offset) . "
        ");
        $stmt->execute([$customerId]);
        $rooms = $stmt->fetchAll();
        
        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

        jsonResponse(true, 'Chat rooms loaded successfully.', ['rooms' => $rooms], $pagination);
    }

    public function createRoom() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $data = json_decode(file_get_contents('php://input'), true);
        $required = ['firebase_chat_id', 'vendor_id'];
        $errors = validateRequired($data, $required);
        if (!empty($errors)) {
            sendError('Validation error', $errors, 422);
        }
        
        $db = Database::getInstance();
        
        // Check if exists
        $stmt = $db->prepare("SELECT id FROM chat_references WHERE firebase_chat_id = ? LIMIT 1");
        $stmt->execute([$data['firebase_chat_id']]);
        if ($stmt->fetchColumn()) {
            sendResponse([], 'Chat reference already exists.');
        }
        
        $stmt = $db->prepare("
            INSERT INTO chat_references (firebase_chat_id, customer_id, vendor_id, maid_id, quotation_request_id, contract_id)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $data['firebase_chat_id'],
            $customerId,
            $data['vendor_id'],
            $data['maid_id'] ?? null,
            $data['quotation_request_id'] ?? null,
            $data['contract_id'] ?? null
        ]);
        
        sendResponse([], 'Chat reference registered successfully.', 201);
    }
}
