<?php
/**
 * Banner API Endpoint
 * GET: Return active banner (public, no auth required)
 * PUT: Upsert banner settings (admin only)
 * POST: Upload banner image (admin only, max 2MB, png/jpg/webp)
 */

require_once __DIR__ . '/../includes/Auth.php';
require_once __DIR__ . '/../includes/Database.php';

header('Content-Type: application/json; charset=utf-8');

$method = $_SERVER['REQUEST_METHOD'];
$baseDir = dirname(__DIR__);

if ($method === 'GET') {
    try {
        $db = Database::getInstance();
        $stmt = $db->query("SELECT * FROM Banner WHERE active = 1 LIMIT 1");
        $banner = $stmt->fetch();

        if (!$banner) {
            echo json_encode(['banner' => null]);
            exit;
        }

        echo json_encode([
            'banner' => [
                'id'        => $banner['id'],
                'adType'    => $banner['adType'],
                'imageUrl'  => $banner['imageUrl'],
                'adCode'    => $banner['adCode'],
                'linkUrl'   => $banner['linkUrl'],
                'text'      => $banner['text'],
                'active'    => (bool)$banner['active'],
                'position'  => $banner['position'],
            ],
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'خطأ في جلب البانر']);
    }
    exit;
}

if ($method === 'PUT') {
    Auth::requireAdmin();

    try {
        $input = json_decode(file_get_contents('php://input'), true);
        $adType   = $input['adType'] ?? 'image';
        $imageUrl = $input['imageUrl'] ?? '';
        $adCode   = $input['adCode'] ?? '';
        $linkUrl  = $input['linkUrl'] ?? '';
        $text     = $input['text'] ?? '';
        $active   = $input['active'] ?? false;
        $position = $input['position'] ?? 'top';

        $db = Database::getInstance();

        // Check if a banner already exists
        $stmt = $db->query("SELECT id FROM Banner LIMIT 1");
        $existing = $stmt->fetch();

        if ($existing) {
            // Update existing banner
            $sql = "UPDATE Banner SET
                        adType = :adType,
                        imageUrl = :imageUrl,
                        adCode = :adCode,
                        linkUrl = :linkUrl,
                        text = :text,
                        active = :active,
                        position = :position,
                        updatedAt = datetime('now')
                    WHERE id = :id";
            $params = [
                ':adType'   => $adType,
                ':imageUrl' => $imageUrl,
                ':adCode'   => $adCode,
                ':linkUrl'  => $linkUrl,
                ':text'     => $text,
                ':active'   => $active ? 1 : 0,
                ':position' => $position,
                ':id'       => $existing['id'],
            ];
        } else {
            // Create new banner
            $id = 'banner-' . bin2hex(random_bytes(8));
            $sql = "INSERT INTO Banner (id, adType, imageUrl, adCode, linkUrl, text, active, position, createdAt, updatedAt)
                    VALUES (:id, :adType, :imageUrl, :adCode, :linkUrl, :text, :active, :position, datetime('now'), datetime('now'))";
            $params = [
                ':id'       => $id,
                ':adType'   => $adType,
                ':imageUrl' => $imageUrl,
                ':adCode'   => $adCode,
                ':linkUrl'  => $linkUrl,
                ':text'     => $text,
                ':active'   => $active ? 1 : 0,
                ':position' => $position,
            ];
        }

        $stmt = $db->prepare($sql);
        $stmt->execute($params);

        // Return the banner
        $stmt = $db->query("SELECT * FROM Banner LIMIT 1");
        $banner = $stmt->fetch();

        echo json_encode([
            'id'        => $banner['id'],
            'adType'    => $banner['adType'],
            'imageUrl'  => $banner['imageUrl'],
            'adCode'    => $banner['adCode'],
            'linkUrl'   => $banner['linkUrl'],
            'text'      => $banner['text'],
            'active'    => (bool)$banner['active'],
            'position'  => $banner['position'],
            'createdAt' => $banner['createdAt'],
            'updatedAt' => $banner['updatedAt'],
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'خطأ في تحديث البانر']);
    }
    exit;
}

if ($method === 'POST') {
    Auth::requireAdmin();

    try {
        if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
            http_response_code(400);
            echo json_encode(['error' => 'لم يتم إرسال صورة']);
            exit;
        }

        $file = $_FILES['image'];
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($file['tmp_name']);

        $allowedTypes = ['image/png', 'image/jpeg', 'image/webp'];
        if (!in_array($mimeType, $allowedTypes)) {
            http_response_code(400);
            echo json_encode(['error' => 'نوع الملف غير مدعوم. استخدم PNG أو JPG أو WEBP']);
            exit;
        }

        $maxSize = defined('MAX_BANNER_SIZE') ? MAX_BANNER_SIZE : (2 * 1024 * 1024);
        if ($file['size'] > $maxSize) {
            http_response_code(400);
            echo json_encode(['error' => 'حجم الصورة كبير جداً. الحد الأقصى 2 ميجا']);
            exit;
        }

        $ext = 'jpg';
        if ($mimeType === 'image/png') $ext = 'png';
        elseif ($mimeType === 'image/webp') $ext = 'webp';

        $bannerDir = $baseDir . '/public/banners';
        if (!is_dir($bannerDir)) {
            mkdir($bannerDir, 0755, true);
        }

        $filename = 'banner_' . bin2hex(random_bytes(8)) . '.' . $ext;
        $destPath = $bannerDir . '/' . $filename;

        if (!move_uploaded_file($file['tmp_name'], $destPath)) {
            http_response_code(500);
            echo json_encode(['error' => 'فشل حفظ الصورة']);
            exit;
        }

        $imageUrl = '/banners/' . $filename;
        echo json_encode(['success' => true, 'imageUrl' => $imageUrl]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'خطأ في رفع صورة البانر']);
    }
    exit;
}

http_response_code(405);
echo json_encode(['error' => 'طريقة الطلب غير مدعومة']);