<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Str;
use App\Services\AccountingService;

class CanvasSetoranController extends Controller
{
    /**
     * Mendapatkan daftar uang setoran kanvas yang masih PENDING & HISTORI HARI INI
     */
    public function getPending(Request $request)
    {
        try {
            $user = $request->user();

            $query = DB::table('sales_orders as so')
                ->join('salesmen as s', 'so.salesman_id', '=', 's.id')
                ->join('users as u', 's.user_id', '=', 'u.id')
                ->where('s.salesman_type', 'CANVAS')
                ->where('so.payment_method', 'cash')
                ->where(function($q) {
                    // Munculkan yang masih menggantung (belum disetor)
                    $q->whereIn('so.status', ['waiting_payment', 'terkirim', 'selesai', 'pending'])
                      // DITAMBAH: Munculkan juga yang sudah diterima, tapi khusus hari ini saja sebagai histori kasir
                      ->orWhere(function($subQ) {
                          $subQ->where('so.status', 'completed')
                               ->whereDate('so.updated_at', Carbon::today());
                      });
                })
                ->select(
                    'so.id',
                    'so.so_number as invoice_number',
                    'so.customer_name',
                    'so.grand_total as amount',
                    'so.created_at',
                    'so.status', // DIBAWA KE FRONTEND UNTUK DETEKSI TOMBOL
                    'u.name as collector_name'
                );

            if ($user && $user->role !== 'owner') {
                $query->where('so.branch_id', $user->branch_id);
            }

            // Diurutkan berdasarkan kapan terakhir di-update, agar yang baru diklik tetap di atas
            $pendingSetoran = $query->orderBy('so.updated_at', 'desc')->get();

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

    /**
     * Memproses penerimaan fisik uang kasir DENGAN INTEGRASI GL BARU
     */
    public function verify(Request $request, $id)
    {
        $request->validate([
            'account_id' => 'required|integer' 
        ]);

        DB::beginTransaction();
        try {
            $user = $request->user();
            
            // Gunakan lockForUpdate untuk mencegah Race Condition (Double Click) di tingkat Database
            $order = DB::table('sales_orders')->where('id', $id)->lockForUpdate()->first();
            
            if (!$order) {
                throw new \Exception('Data faktur kanvas tidak ditemukan.');
            }

            // GEMBOK BAJA: Tolak jika status sudah completed
            if ($order->status === 'completed') {
                throw new \Exception('Setoran ini sudah diproses dan dijurnal sebelumnya. Transaksi ganda ditolak.');
            }

            if ($user && $user->role !== 'owner' && $order->branch_id !== $user->branch_id) {
                throw new \Exception('Akses ditolak: Anda tidak berhak memverifikasi setoran tunai dari cabang lain.');
            }

            if ($user && $user->role !== 'owner') {
                $isMapped = DB::table('branch_accounts')
                    ->where('branch_id', $user->branch_id)
                    ->where('account_id', $request->account_id)
                    ->where('is_active', 1)
                    ->exists();

                if (!$isMapped) {
                    throw new \Exception('Akses ditolak: Akun Kas/Bank tujuan tidak terdaftar untuk cabang Anda.');
                }
            }

            // Update status menjadi completed
            DB::table('sales_orders')->where('id', $id)->update([
                'status' => 'completed',
                'updated_at' => now()
            ]);

            $accCashSales = AccountingService::getAccountId('cash_sales_account');
            
            if (!$accCashSales) {
                throw new \Exception("Konfigurasi Sistem Gagal: Akun Titipan Kas Penjualan belum dikonfigurasi di Master Buku Besar.");
            }

            // Eksekusi Jurnal
            AccountingService::log([
                'branch_id'   => $order->branch_id ?? 1,
                'entry_date'  => date('Y-m-d'),
                'description' => 'Penerimaan Uang Kanvas dari Sales (' . $order->customer_name . ')',
                'reference'   => $order->so_number,
                'source_type' => 'CANVAS_SETTLEMENT',
                'user_id'     => $user ? $user->id : auth()->id(),
                'items'       => [
                    [
                        'account_id' => $request->account_id, 
                        'debit' => $order->grand_total, 
                        'credit' => 0
                    ],
                    [
                        'account_id' => $accCashSales, 
                        'debit' => 0, 
                        'credit' => $order->grand_total
                    ]
                ]
            ]);

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Setoran berhasil diverifikasi dan dijurnal.']);

        } catch (\Exception $e) {
            DB::rollBack();
            // Kembalikan status HTTP 400 agar frontend menangkapnya sebagai error, bukan success
            return response()->json(['success' => false, 'message' => $e->getMessage()], 400);
        }
    }

    /**
     * Mendapatkan rekapitulasi setoran
     */
    public function getSummary(Request $request)
    {
        try {
            $user = $request->user();

            $query = DB::table('sales_orders as so')
                ->join('salesmen as s', 'so.salesman_id', '=', 's.id')
                ->join('users as u', 's.user_id', '=', 'u.id')
                ->whereIn('so.status', ['waiting_payment', 'terkirim', 'selesai', 'completed'])
                ->select(
                    'u.name as salesman_name',
                    DB::raw('SUM(so.grand_total) as total_setoran'),
                    DB::raw('COUNT(so.id) as total_faktur')
                );

            if ($user && $user->role !== 'owner') {
                $query->where('so.branch_id', $user->branch_id);
            }

            $summary = $query->groupBy('u.name')->get();

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