<?php

namespace Modules\Dashboard\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\View;
use Modules\Dashboard\Models\Dashboard;

class DashboardController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('dashboard_view');

        $db = Database::getInstance();
        $today = date('Y-m-d');
        $branchId = Auth::branchId();

        $appointmentsQuery = $db->table('appointments')
            ->where('DATE(start_time)', $today);
        if ($branchId) {
            $appointmentsQuery->where('branch_id', $branchId);
        }
        $todayAppointments = $appointmentsQuery->count();

        $revenueQuery = $db->table('invoices')
            ->where('DATE(created_at)', $today)
            ->whereIn('payment_status', ['paid', 'partial']);
        if ($branchId) {
            $revenueQuery->where('branch_id', $branchId);
        }
        $todayRevenue = $revenueQuery->sum('grand_total');

        $customersQuery = $db->table('customers')
            ->where('status', 'active');
        if ($branchId) {
            $customersQuery->where('branch_id', $branchId);
        }
        $activeCustomers = $customersQuery->count();

        $lowStockQuery = $db->table('products')
            ->whereRaw('current_stock <= reorder_level');
        if ($branchId) {
            $lowStockQuery->where('branch_id', $branchId);
        }
        $lowStockCount = $lowStockQuery->count();

        $apptsQuery = $db->table('appointments a')
            ->select('a.*, c.first_name as customer_first_name, c.last_name as customer_last_name, 
                     c.phone as customer_phone')
            ->leftJoin('customers c', 'a.customer_id', '=', 'c.id')
            ->where('DATE(a.start_time)', $today)
            ->orderBy('a.start_time', 'ASC');
        if ($branchId) {
            $apptsQuery->where('a.branch_id', $branchId);
        }
        $appointments = $apptsQuery->get();

        $this->view('Dashboard/index', [
            'title' => 'Dashboard',
            'todayAppointments' => $todayAppointments,
            'todayRevenue' => $todayRevenue,
            'activeCustomers' => $activeCustomers,
            'lowStockCount' => $lowStockCount,
            'appointments' => $appointments,
            'breadcrumb' => ['Dashboard' => url('dashboard')],
        ]);
    }

    public function stats(): void
    {
        Auth::requirePermission('dashboard_view');

        $db = Database::getInstance();
        $today = date('Y-m-d');
        $branchId = Auth::branchId();

        $revenueQuery = $db->table('invoices')
            ->where('DATE(created_at)', $today)
            ->whereIn('payment_status', ['paid', 'partial']);
        if ($branchId) {
            $revenueQuery->where('branch_id', $branchId);
        }
        $revenueToday = $revenueQuery->sum('grand_total');

        $apptsQuery = $db->table('appointments')
            ->where('DATE(start_time)', $today);
        if ($branchId) {
            $apptsQuery->where('branch_id', $branchId);
        }
        $appointmentsToday = $apptsQuery->count();

        $customersQuery = $db->table('customers')
            ->where('status', 'active');
        if ($branchId) {
            $customersQuery->where('branch_id', $branchId);
        }
        $customersToday = $customersQuery->count();

        $lowStockQuery = $db->table('products')
            ->whereRaw('current_stock <= reorder_level');
        if ($branchId) {
            $lowStockQuery->where('branch_id', $branchId);
        }
        $lowStockCount = $lowStockQuery->count();

        $this->json([
            'success' => true,
            'data' => [
                'revenue_today' => $revenueToday,
                'appointments_today' => $appointmentsToday,
                'customers_today' => $customersToday,
                'low_stock_count' => $lowStockCount,
            ],
        ]);
    }

    public function revenueChart(): void
    {
        Auth::requirePermission('dashboard_view');

        $db = Database::getInstance();
        $branchId = Auth::branchId();
        $labels = [];
        $data = [];

        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $labels[] = date('D', strtotime($date));

            $query = $db->table('invoices')
                ->where('DATE(created_at)', $date)
                ->whereIn('payment_status', ['paid', 'partial']);
            if ($branchId) {
                $query->where('branch_id', $branchId);
            }
            $data[] = $query->sum('grand_total');
        }

        $this->json([
            'success' => true,
            'data' => [
                'labels' => $labels,
                'datasets' => [
                    [
                        'label' => 'Revenue',
                        'data' => $data,
                        'borderColor' => '#C8A44E',
                        'backgroundColor' => 'rgba(200, 164, 78, 0.1)',
                        'fill' => true,
                        'tension' => 0.4,
                    ],
                ],
            ],
        ]);
    }

    public function appointmentsToday(): void
    {
        Auth::requirePermission('dashboard_view');

        $db = Database::getInstance();
        $today = date('Y-m-d');
        $branchId = Auth::branchId();

        $query = $db->table('appointments a')
            ->select('a.*, c.first_name as customer_first_name, c.last_name as customer_last_name,
                     c.phone as customer_phone')
            ->leftJoin('customers c', 'a.customer_id', '=', 'c.id')
            ->where('DATE(a.start_time)', $today)
            ->orderBy('a.start_time', 'ASC');
        if ($branchId) {
            $query->where('a.branch_id', $branchId);
        }
        $appointments = $query->get();

        $this->json([
            'success' => true,
            'data' => $appointments,
        ]);
    }

    public function topServices(): void
    {
        Auth::requirePermission('dashboard_view');

        $db = Database::getInstance();
        $branchId = Auth::branchId();
        $limit = 5;

        $query = "SELECT s.name, COUNT(asv.id) as total_count, COALESCE(SUM(asv.price), 0) as total_revenue
                  FROM appointment_services asv
                  INNER JOIN services s ON asv.service_id = s.id
                  INNER JOIN appointments a ON asv.appointment_id = a.id
                  WHERE a.deleted_at IS NULL AND a.status = 'completed'";
        $bindings = [];
        if ($branchId) {
            $query .= " AND a.branch_id = :branch_id";
            $bindings[':branch_id'] = $branchId;
        }
        $query .= " GROUP BY s.id, s.name ORDER BY total_revenue DESC LIMIT " . (int)$limit;
        $data = $db->query($query, $bindings);

        $this->json(['success' => true, 'data' => $data]);
    }

    public function lowStockData(): void
    {
        Auth::requirePermission('dashboard_view');

        $db = Database::getInstance();
        $branchId = Auth::branchId();

        $query = $db->table('products')
            ->select('id, name, current_stock as quantity')
            ->whereRaw('current_stock <= reorder_level')
            ->orderBy('current_stock', 'ASC')
            ->limit(5);
        if ($branchId) {
            $query->where('branch_id', $branchId);
        }
        $data = $query->get();

        $this->json(['success' => true, 'data' => $data]);
    }

    public function topEmployees(): void
    {
        Auth::requirePermission('dashboard_view');

        $db = Database::getInstance();
        $branchId = Auth::branchId();
        $limit = 5;

        $query = "SELECT e.id, e.first_name, e.last_name, 
                  COUNT(DISTINCT a.id) as total_appointments, COALESCE(SUM(asv.price), 0) as total_revenue
                  FROM appointments a
                  INNER JOIN appointment_services asv ON a.id = asv.appointment_id
                  INNER JOIN employees e ON asv.employee_id = e.id
                  WHERE a.deleted_at IS NULL AND a.status = 'completed'";
        $bindings = [];
        if ($branchId) {
            $query .= " AND a.branch_id = :branch_id";
            $bindings[':branch_id'] = $branchId;
        }
        $query .= " GROUP BY e.id, e.first_name, e.last_name ORDER BY total_revenue DESC LIMIT " . (int)$limit;
        $data = $db->query($query, $bindings);

        $this->json(['success' => true, 'data' => $data]);
    }
}
