<?php

namespace App\Controllers\Admin;

use App\Controllers\AdminController;
use App\Models\ShortlinkModel;
use App\Models\ShortlinkHistoryModel;
use App\Models\UserModel;

class Shortlinks extends AdminController
{
    public function index()
    {
        $shortlinkModel = new ShortlinkModel();
        $shortlinkHistoryModel = new ShortlinkHistoryModel();
        
        // Get search parameters
        $search = $this->request->getGet('search') ?? '';
        $sort = $this->request->getGet('sort') ?? 'id';
        $order = $this->request->getGet('order') ?? 'DESC';
        
        // Get pagination parameters
        $page = $this->request->getGet('page') ?? 1;
        $perPage = 20;
        $offset = ($page - 1) * $perPage;
        
        // Build query
        $query = $shortlinkModel;
        
        // Apply search filter
        if (!empty($search)) {
            $query = $query->groupStart()
                          ->like('name', $search)
                          ->orLike('id', $search)
                          ->groupEnd();
        }
        
        // Apply sorting - map title to name, created_at to id (since there's no created_at)
        $sortColumn = $sort === 'title' ? 'name' : ($sort === 'created_at' ? 'id' : $sort);
        $query = $query->orderBy($sortColumn, $order);
        
        // Get shortlinks with pagination
        $shortlinks = $query->findAll($perPage, $offset);
        $totalShortlinks = $query->countAllResults(false);
        
        // Get additional data for each shortlink (use view column from shortlink table)
        foreach ($shortlinks as &$shortlink) {
            $shortlink['total_views'] = $shortlink['view'] ?? 0;
        }
        
        // Get statistics in one optimized query
        $today = date('Y-m-d');
        $shortlinkStats = $shortlinkModel->select('
            COUNT(*) as total_shortlinks,
            SUM(view) as total_views
        ')->first();
        
        $todayViews = $shortlinkHistoryModel->where('DATE(time_stamp)', $today)->countAllResults();
        
        $stats = [
            'total_shortlinks' => $shortlinkStats['total_shortlinks'] ?? 0,
            'active_shortlinks' => $shortlinkStats['total_shortlinks'] ?? 0, // No status column, so all are considered active
            'total_views' => $shortlinkStats['total_views'] ?? 0,
            'today_views' => $todayViews
        ];
        
        $this->data['shortlinks'] = $shortlinks;
        $this->data['stats'] = $stats;
        $this->data['pagination'] = [
            'current_page' => $page,
            'total_pages' => ceil($totalShortlinks / $perPage),
            'total_shortlinks' => $totalShortlinks,
            'per_page' => $perPage
        ];
        $this->data['filters'] = [
            'search' => $search,
            'sort' => $sort,
            'order' => $order
        ];
        
        $this->data['title'] = 'Shortlinks Management';
        return $this->render_admin('admin/shortlinks', $this->data);
    }
    
    public function add()
    {
        if ($this->request->getMethod() === 'post') {
            $shortlinkModel = new ShortlinkModel();
            
            $data = [
                'name' => $this->request->getPost('title'),
                'reward' => $this->request->getPost('reward'),
                'view' => $this->request->getPost('views'),
                'api_key' => $this->request->getPost('api_key') ?? '',
                'priority' => $this->request->getPost('priority') ?? 1
            ];
            
            if ($shortlinkModel->insert($data)) {
                return redirect()->to('/admin/shortlinks')->with('success', 'Shortlink added successfully!');
            } else {
                return redirect()->to('/admin/shortlinks')->with('error', 'Failed to add shortlink!');
            }
        }
        
        // If not POST, redirect to index page
        return redirect()->to('/admin/shortlinks');
    }
    
    public function edit($id)
    {
        $shortlinkModel = new ShortlinkModel();
        $shortlink = $shortlinkModel->find($id);
        
        if (!$shortlink) {
            return redirect()->to('/admin/shortlinks')->with('error', 'Shortlink not found!');
        }
        
        if ($this->request->getMethod() === 'post') {
            $data = [
                'name' => $this->request->getPost('title'),
                'reward' => $this->request->getPost('reward'),
                'view' => $this->request->getPost('views'),
                'api_key' => $this->request->getPost('api_key') ?? '',
                'priority' => $this->request->getPost('priority') ?? 1
            ];
            
            if ($shortlinkModel->update($id, $data)) {
                return redirect()->to('/admin/shortlinks')->with('success', 'Shortlink updated successfully!');
            } else {
                return redirect()->to('/admin/shortlinks')->with('error', 'Failed to update shortlink!');
            }
        }
        
        $this->data['shortlink'] = $shortlink;
        $this->data['title'] = 'Edit Shortlink';
        return $this->render_admin('admin/shortlink-form', $this->data);
    }
    
    public function delete($id)
    {
        $shortlinkModel = new ShortlinkModel();
        
        if ($shortlinkModel->delete($id)) {
            return redirect()->to('/admin/shortlinks')->with('success', 'Shortlink deleted successfully!');
        } else {
            return redirect()->to('/admin/shortlinks')->with('error', 'Failed to delete shortlink!');
        }
    }
    
    public function toggleStatus($id)
    {
        // Since the model doesn't have a status column, we'll skip this functionality
        // or implement it differently based on your needs
        return redirect()->to('/admin/shortlinks');
    }
    
    public function claims()
    {
        $shortlinkHistoryModel = new ShortlinkHistoryModel();
        $userModel = new UserModel();
        
        // Get search parameters
        $search = $this->request->getGet('search') ?? '';
        $sort = $this->request->getGet('sort') ?? 'id';
        $order = $this->request->getGet('order') ?? 'DESC';
        
        // Get pagination parameters
        $page = $this->request->getGet('page') ?? 1;
        $perPage = 20;
        $offset = ($page - 1) * $perPage;
        
        // Build query with JOIN to get user email
        $query = $shortlinkHistoryModel->select('link_history.*, users.email as user_email')
                                     ->join('users', 'users.id = link_history.user_id', 'left');
        
        // Apply search filter
        if (!empty($search)) {
            $query = $query->groupStart()
                          ->like('users.email', $search)
                          ->orLike('link_history.id', $search)
                          ->orLike('link_history.url', $search)
                          ->groupEnd();
        }
        
        // Apply sorting - map created_at to time_stamp
        $sortColumn = $sort === 'created_at' ? 'time_stamp' : $sort;
        $query = $query->orderBy($sortColumn, $order);
        
        // Get claims with pagination
        $claims = $query->findAll($perPage, $offset);
        $totalClaims = $query->countAllResults(false);
        
        // Get statistics in one optimized query
        $today = date('Y-m-d');
        $claimsStats = $shortlinkHistoryModel->select('
            COUNT(*) as total_claims,
            SUM(reward) as total_reward,
            SUM(CASE WHEN DATE(time_stamp) = "' . $today . '" THEN 1 ELSE 0 END) as today_claims,
            SUM(CASE WHEN DATE(time_stamp) = "' . $today . '" THEN reward ELSE 0 END) as today_reward
        ')->first();
        
        $stats = [
            'total_claims' => $claimsStats['total_claims'] ?? 0,
            'today_claims' => $claimsStats['today_claims'] ?? 0,
            'total_reward' => $claimsStats['total_reward'] ?? 0,
            'today_reward' => $claimsStats['today_reward'] ?? 0
        ];
        
        $this->data['claims'] = $claims;
        $this->data['stats'] = $stats;
        $this->data['pagination'] = [
            'current_page' => $page,
            'total_pages' => ceil($totalClaims / $perPage),
            'total_claims' => $totalClaims,
            'per_page' => $perPage
        ];
        $this->data['filters'] = [
            'search' => $search,
            'sort' => $sort,
            'order' => $order
        ];
        
        $this->data['title'] = 'Shortlink Claims';
        return $this->render_admin('admin/shortlink-claims', $this->data);
    }
}
