<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\JournalEntry;
use Illuminate\Http\Request;

class JournalApiController extends Controller
{
    public function index(Request $request)
    {
        try {
            $user = $request->user(); // PENAMBAHAN: Identifikasi user yang request

            // Menggunakan nama tabel sesuai database: journal_entries dan journal_items
            $query = \DB::table('journal_entries as h')
                ->join('journal_items as d', 'h.id', '=', 'd.journal_entry_id')
                ->join('accounts as a', 'd.account_id', '=', 'a.id')
                ->select(
                    'h.id',
                    'h.entry_date as transaction_date', // Menggunakan kolom entry_date
                    'h.description',
                    'h.source_type as reference_type',  // Menggunakan kolom source_type
                    'h.reference as reference_id',      // Menggunakan kolom reference
                    'a.code as account_code',
                    'a.name as account_name',
                    'd.debit',
                    'd.credit'
                );

            // =========================================================================
            // PERBAIKAN ENTERPRISE: Isolasi Cabang Buku Besar (Branch Data Isolation)
            // =========================================================================
            // 1. Jika bukan Owner, kunci mutlak hanya bisa melihat jurnal cabangnya sendiri
            if ($user && $user->role !== 'owner') {
                $query->where('h.branch_id', $user->branch_id);
            } 
            // 2. Jika Owner, izinkan filter berdasarkan parameter branch_id dari UI
            elseif ($request->filled('branch_id')) {
                $query->where('h.branch_id', $request->branch_id);
            }
            // =========================================================================

            // =========================================================================
            // FIX BUG: Tangkap Parameter Filter dari Frontend
            // =========================================================================
            if ($request->filled('search')) {
                $search = $request->search;
                $query->where(function($q) use ($search) {
                    $q->where('h.reference', 'like', "%{$search}%")
                      ->orWhere('h.description', 'like', "%{$search}%")
                      ->orWhere('a.code', 'like', "%{$search}%")
                      ->orWhere('a.name', 'like', "%{$search}%");
                });
            }

            if ($request->filled('start_date')) {
                $query->whereDate('h.entry_date', '>=', $request->start_date);
            }

            if ($request->filled('end_date')) {
                $query->whereDate('h.entry_date', '<=', $request->end_date);
            }
            // =========================================================================

            $data = $query->orderBy('h.entry_date', 'desc')
                ->orderBy('h.id', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
}