<?php

require_once __DIR__ . '/BaseController.php';
require_once __DIR__ . '/../models/BannerModel.php';

class BannerController extends BaseController
{

    private $bannerModel;

    public function __construct()
    {
        parent::__construct();
        $this->bannerModel = new BannerModel();
    }

    /**
     * Get all active banners
     */
    public function getBanners()
    {
        try {
            $this->allowMethod(['GET']);

            $queryParams = $this->getQueryParams();
            $idMitra = isset($queryParams['id_mitra']) ? (int) $queryParams['id_mitra'] : 1;
            $limit = isset($queryParams['limit']) ? (int) $queryParams['limit'] : null;

            $banners = $this->bannerModel->getActiveBanners($idMitra, $limit);

            Response::success('Banners retrieved successfully', [
                'banners' => $banners,
                'count' => count($banners)
            ]);
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Get banner by ID
     */
    public function getBannerById()
    {
        try {
            $this->allowMethod(['GET']);

            $queryParams = $this->getQueryParams();

            if (!isset($queryParams['id']) || !is_numeric($queryParams['id'])) {
                Response::validationError('Banner ID is required and must be numeric');
            }

            $id = (int) $queryParams['id'];
            $idMitra = isset($queryParams['id_mitra']) ? (int) $queryParams['id_mitra'] : 1;

            if ($id <= 0) {
                Response::validationError('Invalid banner ID');
            }

            $banner = $this->bannerModel->getBannerById($id, $idMitra);

            if ($banner) {
                Response::success('Banner retrieved successfully', $banner);
            } else {
                Response::notFound('Banner not found or inactive');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Save banner click
     */
    public function saveBannerClick()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['user_id', 'id_mitra']);

            $userId = (int) $data['user_id'];
            $idMitra = (int) $data['id_mitra'];

            if ($userId <= 0 || $idMitra <= 0) {
                Response::validationError('Invalid user_id or id_mitra');
            }

            // Validate if user exists
            if (!$this->bannerModel->userExists($userId)) {
                Response::notFound('User not found');
            }

            $clickId = $this->bannerModel->saveBannerClick($userId, $idMitra);

            if ($clickId) {
                Response::success('Banner click saved successfully', [
                    'click_id' => $clickId,
                    'user_id' => $userId,
                    'id_mitra' => $idMitra,
                    'timestamp' => date('Y-m-d H:i:s')
                ]);
            } else {
                Response::error('Failed to save banner click');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Get banner click statistics
     */
    public function getBannerClickStats()
    {
        try {
            $this->allowMethod(['GET']);

            $queryParams = $this->getQueryParams();
            $this->validateRequired($queryParams, ['id_mitra']);

            $idMitra = (int) $queryParams['id_mitra'];
            $dateFrom = $queryParams['date_from'] ?? null;
            $dateTo = $queryParams['date_to'] ?? null;

            if ($idMitra <= 0) {
                Response::validationError('Invalid id_mitra');
            }

            // Validate date format if provided
            if ($dateFrom && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateFrom)) {
                Response::validationError('Invalid date_from format. Use YYYY-MM-DD');
            }

            if ($dateTo && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateTo)) {
                Response::validationError('Invalid date_to format. Use YYYY-MM-DD');
            }

            $stats = $this->bannerModel->getBannerClickStats($idMitra, $dateFrom, $dateTo);

            // Calculate totals
            $totalClicks = array_sum(array_column($stats, 'total_clicks'));
            $totalUniqueUsers = count(array_unique(array_column($stats, 'unique_users')));

            Response::success('Banner click statistics retrieved successfully', [
                'id_mitra' => $idMitra,
                'date_from' => $dateFrom,
                'date_to' => $dateTo,
                'summary' => [
                    'total_clicks' => $totalClicks,
                    'total_unique_users' => $totalUniqueUsers,
                    'days_tracked' => count($stats)
                ],
                'daily_stats' => $stats
            ]);
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Create new banner (admin function)
     */
    public function createBanner()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['title', 'description', 'image_url', 'id_mitra']);

            $bannerData = [
                'title' => trim($data['title']),
                'description' => trim($data['description']),
                'image_url' => trim($data['image_url']),
                'link_url' => trim($data['link_url'] ?? ''),
                'id_mitra' => (int) $data['id_mitra'],
                'display_order' => (int) ($data['display_order'] ?? 0),
                'is_active' => isset($data['is_active']) ? (bool) $data['is_active'] : true,
                'valid_until' => $data['valid_until'] ?? null
            ];

            // Sanitize data
            $bannerData = $this->sanitizeInput($bannerData);

            // Validate URLs
            if (!filter_var($bannerData['image_url'], FILTER_VALIDATE_URL)) {
                Response::validationError('Invalid image URL');
            }

            if (!empty($bannerData['link_url']) && !filter_var($bannerData['link_url'], FILTER_VALIDATE_URL)) {
                Response::validationError('Invalid link URL');
            }

            $bannerId = $this->bannerModel->createBanner($bannerData);

            if ($bannerId) {
                Response::success('Banner created successfully', [
                    'banner_id' => $bannerId,
                    'message' => 'Banner has been created and is now active'
                ], 201);
            } else {
                Response::error('Failed to create banner');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Update banner (admin function)
     */
    public function updateBanner()
    {
        try {
            $this->allowMethod(['POST', 'PUT']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['id']);

            $bannerId = (int) $data['id'];

            if ($bannerId <= 0) {
                Response::validationError('Invalid banner ID');
            }

            // Check if banner exists
            if (!$this->bannerModel->find($bannerId)) {
                Response::notFound('Banner not found');
            }

            // Prepare update data (only include provided fields)
            $updateData = [];
            $allowedFields = ['title', 'description', 'image_url', 'link_url', 'display_order', 'is_active', 'valid_until'];

            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $updateData[$field] = $data[$field];
                }
            }

            if (empty($updateData)) {
                Response::validationError('No valid fields provided for update');
            }

            // Sanitize data
            $updateData = $this->sanitizeInput($updateData);

            // Validate URLs if provided
            if (isset($updateData['image_url']) && !filter_var($updateData['image_url'], FILTER_VALIDATE_URL)) {
                Response::validationError('Invalid image URL');
            }

            if (isset($updateData['link_url']) && !empty($updateData['link_url']) && !filter_var($updateData['link_url'], FILTER_VALIDATE_URL)) {
                Response::validationError('Invalid link URL');
            }

            $result = $this->bannerModel->updateBanner($bannerId, $updateData);

            if ($result) {
                Response::success('Banner updated successfully');
            } else {
                Response::error('Failed to update banner or no changes made');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Delete/Deactivate banner (admin function)
     */
    public function deleteBanner()
    {
        try {
            $this->allowMethod(['POST', 'DELETE']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['id']);

            $bannerId = (int) $data['id'];

            if ($bannerId <= 0) {
                Response::validationError('Invalid banner ID');
            }

            // Check if banner exists
            if (!$this->bannerModel->find($bannerId)) {
                Response::notFound('Banner not found');
            }

            // Deactivate instead of delete to preserve click data
            $result = $this->bannerModel->deactivateBanner($bannerId);

            if ($result) {
                Response::success('Banner deactivated successfully');
            } else {
                Response::error('Failed to deactivate banner');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }
}
