<?php

namespace App\Http\Controllers;

use App\Models\FinanceRecord;
use App\Models\FinanceCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FinanceRecordController extends Controller
{
    public function index(Request $request) 
{
    $user = auth()->user();

    // Base Query
    $baseQuery = FinanceRecord::forUser($user->id)->with('categoryInfo');
    

    // Filters
    if ($request->filled('type')) {
        $baseQuery->where('type', $request->type);
    }

    if ($request->filled('category')) {
        $baseQuery->where('category', $request->category);
    }

    if ($request->filled('month')) {
        $baseQuery->forMonth($request->month);
    }

    if ($request->filled('search')) {
        $search = $request->search;
        $baseQuery->where(function ($q) use ($search) {
            $q->where('note', 'like', "%{$search}%")
              ->orWhere('amount', 'like', "%{$search}%");
        });
    }

    // Clone สำหรับ Stats (ไม่ paginate)
    $statsQuery = clone $baseQuery;

    // คำนวณ Stats Cards
    $totalIncome = (clone $statsQuery)->where('type', 'income')->sum('amount');
    $totalExpense = (clone $statsQuery)->where('type', 'expense')->sum('amount');
    $netAmount = $totalIncome - $totalExpense;

    // เปอร์เซ็นต์เปลี่ยนแปลงเทียบเดือนก่อน
    $lastMonthIncome = 0; // TODO: Query เดือนก่อน
    $lastMonthExpense = 0;
    $incomeChange = $lastMonthIncome > 0 
        ? (($totalIncome - $lastMonthIncome) / $lastMonthIncome) * 100 
        : 0;
    $expenseChange = $lastMonthExpense > 0 
        ? (($totalExpense - $lastMonthExpense) / $lastMonthExpense) * 100 
        : 0;

    // Records (paginate)
    $records = $baseQuery->orderBy('record_date', 'desc')
                         ->orderBy('created_at', 'desc')
                         ->paginate(20);

    // Categories
    $categories = FinanceCategory::getGroupedCategories();

    return view('finance.records.index', compact(
        'records', 
        'categories',
        'totalIncome',
        'totalExpense',
        'netAmount',
        'incomeChange',
        'expenseChange'
    ));
}

protected function getAvailableMonths()
{
    $months = [];
    $start = Carbon::now()->subMonths(12); // ย้อนหลัง 12 เดือน
    $end = Carbon::now()->addMonth(); // ล่วงหน้า 1 เดือน (optional)

    while ($start <= $end) {
        $months[] = [
            'value' => $start->format('Y-m'),
            'label' => $start->translatedFormat('F Y'), // ex: สิงหาคม 2025
        ];
        $start->addMonth();
    }

    return array_reverse($months); // ปัจจุบันอยู่บนสุด
}



    public function create(Request $request)
    {
        $type = $request->input('type', 'expense');
        $categories = FinanceCategory::getCategoryOptions($type);
        
        return view('finance.records.create', compact('type', 'categories'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'record_date' => 'required|date',
            'type' => 'required|in:income,expense',
            'category' => 'required|string',
            'amount' => 'required|numeric|min:0',
            'note' => 'nullable|string|max:500',
            'is_recurring' => 'boolean',
            'recurring_type' => 'required_if:is_recurring,true|in:daily,weekly,monthly,yearly',
        ], [
            'record_date.required' => 'กรุณาเลือกวันที่',
            'type.required' => 'กรุณาเลือกประเภท',
            'category.required' => 'กรุณาเลือกหมวดหมู่',
            'amount.required' => 'กรุณาระบุจำนวนเงิน',
            'amount.min' => 'จำนวนเงินต้องมากกว่า 0',
        ]);

        DB::beginTransaction();
        try {
            $data = $request->all();
            $data['user_id'] = auth()->id();
            $data['source'] = 'manual';

            $record = FinanceRecord::create($data);

            // Handle recurring records
            if ($request->boolean('is_recurring')) {
                $this->createRecurringRecords($record, $request->recurring_type);
            }

            DB::commit();

            return redirect()->route('finance.records.index')
                ->with('success', 'บันทึกรายการเรียบร้อยแล้ว');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->withErrors(['error' => 'เกิดข้อผิดพลาดในการบันทึก'])
                        ->withInput();
        }
    }

    public function edit(FinanceRecord $record)
    {
        // Check ownership
        if ($record->user_id !== auth()->id()) {
            abort(403);
        }

        // Cannot edit delivery source records
        if ($record->source === 'delivery') {
            return back()->with('error', 'ไม่สามารถแก้ไขรายการที่มาจากระบบจัดส่งได้');
        }

        $categories = FinanceCategory::getCategoryOptions($record->type);

        return view('finance.records.edit', compact('record', 'categories'));
    }

    public function update(Request $request, FinanceRecord $record)
    {
        // Check ownership
        if ($record->user_id !== auth()->id()) {
            abort(403);
        }

        // Cannot edit delivery source records
        if ($record->source === 'delivery') {
            return back()->with('error', 'ไม่สามารถแก้ไขรายการที่มาจากระบบจัดส่งได้');
        }

        $request->validate([
            'record_date' => 'required|date',
            'category' => 'required|string',
            'amount' => 'required|numeric|min:0',
            'note' => 'nullable|string|max:500',
        ]);

        $record->update($request->only(['record_date', 'category', 'amount', 'note']));

        return redirect()->route('finance.records.index')
            ->with('success', 'อัปเดตรายการเรียบร้อยแล้ว');
    }

    public function destroy(FinanceRecord $record)
    {
        // Check ownership
        if ($record->user_id !== auth()->id()) {
            abort(403);
        }

        // Cannot delete delivery source records
        if ($record->source === 'delivery') {
            return response()->json([
                'success' => false,
                'message' => 'ไม่สามารถลบรายการที่มาจากระบบจัดส่งได้'
            ], 403);
        }

        $record->delete();

        return response()->json([
            'success' => true,
            'message' => 'ลบรายการเรียบร้อยแล้ว'
        ]);
    }

    public function bulkDelete(Request $request)
    {
        $ids = $request->input('ids', []);
        
        // Delete only manual records owned by user
        $deleted = FinanceRecord::whereIn('id', $ids)
            ->where('user_id', auth()->id())
            ->where('source', 'manual')
            ->delete();

        return response()->json([
            'success' => true,
            'message' => "ลบ {$deleted} รายการเรียบร้อยแล้ว"
        ]);
    }

    public function duplicate(FinanceRecord $record)
    {
        // Check ownership
        if ($record->user_id !== auth()->id()) {
            abort(403);
        }

        $newRecord = $record->replicate();
        $newRecord->record_date = now();
        $newRecord->source = 'manual';
        $newRecord->ref_id = null;
        $newRecord->save();

        return response()->json([
            'success' => true,
            'message' => 'คัดลอกรายการเรียบร้อยแล้ว',
            'redirect' => route('finance.records.edit', $newRecord)
        ]);
    }

    private function createRecurringRecords(FinanceRecord $baseRecord, $recurringType)
    {
        $dates = [];
        $endDate = now()->addMonths(3); // Create for next 3 months

        switch ($recurringType) {
            case 'daily':
                $current = $baseRecord->record_date->copy()->addDay();
                while ($current <= $endDate) {
                    $dates[] = $current->copy();
                    $current->addDay();
                }
                break;

            case 'weekly':
                $current = $baseRecord->record_date->copy()->addWeek();
                while ($current <= $endDate) {
                    $dates[] = $current->copy();
                    $current->addWeek();
                }
                break;

            case 'monthly':
                $current = $baseRecord->record_date->copy()->addMonth();
                while ($current <= $endDate) {
                    $dates[] = $current->copy();
                    $current->addMonth();
                }
                break;

            case 'yearly':
                $dates[] = $baseRecord->record_date->copy()->addYear();
                break;
        }

        foreach ($dates as $date) {
            $data = $baseRecord->toArray();
            unset($data['id'], $data['created_at'], $data['updated_at']);
            $data['record_date'] = $date;
            $data['note'] = ($data['note'] ?? '') . ' (รายการซ้ำ)';
            
            FinanceRecord::create($data);
        }
    }

    public function getCategories(Request $request)
    {
        $type = $request->input('type');
        $categories = FinanceCategory::active()
            ->where('type', $type)
            ->ordered()
            ->get();

        return response()->json($categories);
    }
}