<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Reservasi;
use App\Models\Meja;
use Illuminate\Support\Facades\Auth;
use App\Models\Transaksi;

class AdminController extends Controller
{
    public function dashboard(Request $request)
    {
        $period = $request->get('period', 'daily'); // daily, weekly, monthly, yearly

        // Get date ranges based on period
        $dateRange = $this->getDateRange($period);
        $startDate = $dateRange['start'];
        $endDate = $dateRange['end'];

        // Mengambil data untuk dashboard dengan filter periode
        $totalReservasi = Reservasi::whereBetween('created_at', [$startDate, $endDate])->count();
        
        // Menghitung total pendapatan dari transaksi yang sudah dibayar (paid) atau selesai (completed)
        $totalPendapatan = Transaksi::whereIn('status', ['paid', 'completed'])
            ->whereBetween('created_at', [$startDate, $endDate])
            ->sum('total_amount');
        
        // Menghitung jumlah meja yang tersedia
        $mejaKosong = Meja::where('status', 'tersedia')->count();

        // Menghitung jumlah reservasi berdasarkan status dengan filter periode
        $reservasiSuccess = Reservasi::whereIn('status', ['confirmed', 'completed'])
            ->whereBetween('created_at', [$startDate, $endDate])
            ->count();
        $reservasiPending = Reservasi::where('status', 'pending')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->count();
        $reservasiCancelled = Reservasi::where('status', 'cancelled')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->count();

        // Data untuk chart default (tampilan hari ini per jam)
        $chartData = $this->getChartData($period);

        return view('admin.dashboard', compact(
            'totalReservasi', 
            'totalPendapatan', 
            'mejaKosong',
            'reservasiSuccess',
            'reservasiPending',
            'reservasiCancelled',
            'chartData',
            'period'
        ));
    }

    private function getDateRange($period)
    {
        $now = now();
        
        switch ($period) {
            case 'daily':
                return [
                    'start' => $now->startOfDay(),
                    'end' => $now->copy()->endOfDay(),
                ];
            case 'weekly':
                return [
                    'start' => $now->startOfWeek(),
                    'end' => $now->copy()->endOfWeek(),
                ];
            case 'monthly':
                return [
                    'start' => $now->startOfMonth(),
                    'end' => $now->copy()->endOfMonth(),
                ];
            case 'yearly':
                return [
                    'start' => $now->startOfYear(),
                    'end' => $now->copy()->endOfYear(),
                ];
            default:
                return [
                    'start' => $now->startOfDay(),
                    'end' => $now->copy()->endOfDay(),
                ];
        }
    }

    public function getChartData($period = 'daily')
    {
        $query = Transaksi::whereIn('status', ['paid', 'completed']);
        $dateRange = $this->getDateRange($period);
        
        switch ($period) {
            case 'daily':
                // Data per jam untuk hari ini
                $data = $query->whereBetween('created_at', [$dateRange['start'], $dateRange['end']])
                    ->selectRaw('HOUR(created_at) as label, SUM(total_amount) as value')
                    ->groupBy('label')
                    ->orderBy('label')
                    ->get()
                    ->map(function ($item) {
                        return [
                            'label' => sprintf('%02d:00', $item->label),
                            'value' => $item->value
                        ];
                    });
                break;

            case 'weekly':
                // Data per hari dalam minggu ini
                $data = $query->whereBetween('created_at', [$dateRange['start'], $dateRange['end']])
                    ->selectRaw('DATE(created_at) as label, SUM(total_amount) as value')
                    ->groupBy('label')
                    ->orderBy('label')
                    ->get()
                    ->map(function ($item) {
                        return [
                            'label' => date('D, d M', strtotime($item->label)),
                            'value' => $item->value
                        ];
                    });
                break;

            case 'monthly':
                // Data per minggu dalam bulan ini
                $data = $query->whereBetween('created_at', [$dateRange['start'], $dateRange['end']])
                    ->selectRaw('WEEK(created_at) as week, SUM(total_amount) as value')
                    ->groupBy('week')
                    ->orderBy('week')
                    ->get()
                    ->map(function ($item) {
                        $weekStart = now()->setISODate(now()->year, $item->week);
                        return [
                            'label' => 'Minggu ' . $weekStart->format('W'),
                            'value' => $item->value
                        ];
                    });
                break;

            case 'yearly':
                // Data per bulan dalam tahun ini
                $data = $query->whereBetween('created_at', [$dateRange['start'], $dateRange['end']])
                    ->selectRaw('MONTH(created_at) as month, SUM(total_amount) as value')
                    ->groupBy('month')
                    ->orderBy('month')
                    ->get()
                    ->map(function ($item) {
                        return [
                            'label' => date('F', mktime(0, 0, 0, $item->month, 1)),
                            'value' => $item->value
                        ];
                    });
                break;

            default:
                $data = collect([]);
        }

        // Format response
        return [
            'labels' => $data->pluck('label'),
            'values' => $data->pluck('value'),
        ];
    }

    public function ajaxChartData(Request $request)
    {
        $period = $request->get('period', 'daily');
        return response()->json($this->getChartData($period));
    }

    public function reservations()
    {
        // Menampilkan daftar reservasi
        $reservations = Reservasi::latest()->paginate(10);
        return view('admin.reservations', compact('reservations'));
    }

    public function tables()
    {
        // Menampilkan daftar meja
        $tables = Meja::all();
        return view('admin.tables', compact('tables'));
    }

    public function logout(Request $request)
    {
        Auth::logout();
        return redirect('/login')->with('success', 'Berhasil logout');
    }
}

