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

class SupportController {
    
    public function listTickets() {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $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 support_tickets WHERE user_type = 'vendor' AND user_id = ?");
        $totalStmt->execute([$vendorId]);
        $total = (int) $totalStmt->fetchColumn();

        $stmt = $db->prepare("
            SELECT * FROM support_tickets 
            WHERE user_type = 'vendor' AND user_id = ? 
            ORDER BY created_at DESC
            LIMIT " . intval($limit) . " OFFSET " . intval($offset) . "
        ");
        $stmt->execute([$vendorId]);
        $tickets = $stmt->fetchAll();
        
        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

        jsonResponse(true, 'Support tickets loaded.', ['tickets' => $tickets], $pagination);
    }

    public function createTicket() {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];
        
        $data = json_decode(file_get_contents('php://input'), true);
        $errors = validateRequired($data, ['subject', 'message']);
        if (!empty($errors)) {
            sendError('Validation error', $errors, 422);
        }
        
        $db = Database::getInstance();
        $stmt = $db->prepare("
            INSERT INTO support_tickets (user_type, user_id, subject, message, status) 
            VALUES ('vendor', ?, ?, ?, 'open')
        ");
        $stmt->execute([$vendorId, htmlspecialchars($data['subject']), htmlspecialchars($data['message'])]);
        
        sendResponse([], 'Support ticket created successfully.', 201);
    }
}
