<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class AdminSalesController extends Controller
{
    public function daily()
    {
        $this->checkPermission();
        $db = Database::getInstance()->getConnection();
        
        $date = $_GET['date'] ?? date('Y-m-d');
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            $date = date('Y-m-d');
        }

        $stmt = $db->prepare("SELECT SUM(total_amount) as total, COUNT(*) as count, payment_method FROM orders WHERE DATE(created_at) = ? GROUP BY payment_method");
        $stmt->execute([$date]);
        $salesByMethod = $stmt->fetchAll();
        
        $totalSales = 0;
        foreach($salesByMethod as $s) {
            $totalSales += $s['total'];
        }

        $this->view('admin.sales_daily', [
            'salesByMethod' => $salesByMethod,
            'totalSales' => $totalSales,
            'selectedDate' => $date,
        ]);
    }
}
