<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Purchase;
use App\Models\Supplier;
use App\Models\Branch;
use App\Services\AccountingService; 
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class MigrationSupplierDebtApiController extends Controller
{
    // --- 1. AMBIL DAFTAR HUTANG AWAL ---
    public function index(Request $request)
    {
        try {
            $user = $request->user();

            $query = Purchase::with(['supplier', 'branch'])
                ->where('is_initial_debt', true);

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

            $data = $query->orderBy('created_at', 'desc')->get();

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

    // --- 2. AMBIL DATA SUPPLIER ---
    public function getSuppliers()
    {
        try {
            $suppliers = Supplier::orderBy('name', 'asc')->get();
            return response()->json([
                'success' => true,
                'data' => $suppliers
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal memuat supplier: ' . $e->getMessage()
            ], 500);
        }
    }

    // --- 3. AMBIL DATA CABANG ---
    public function getBranches(Request $request)
    {
        try {
            $user = $request->user();
            $query = Branch::query();

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

            $branches = $query->get();

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

    // --- 4. INPUT MANUAL ---
    public function storeManual(Request $request)
    {
        $request->validate([
            'supplier_id' => 'required|exists:suppliers,id',
            'branch_id' => 'required|exists:branches,id',
            'invoice_number' => 'required|string|unique:purchases,invoice_number',
            'grand_total' => 'required|numeric|min:1',
            'purchase_date' => 'required|date',
            'due_date' => 'required|date',
        ]);

        $user = $request->user();

        if ($user && $user->role !== 'owner' && (int)$request->branch_id !== (int)$user->branch_id) {
            return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak dapat menginput hutang untuk cabang lain.'], 403);
        }

        $supplier = Supplier::find($request->supplier_id);
        if (!$supplier) {
            return response()->json(['success' => false, 'message' => 'Supplier tidak ditemukan.'], 404);
        }

        DB::beginTransaction();
        try {
            $purchase = new Purchase();
            $purchase->branch_id = $request->branch_id;
            $purchase->supplier_id = $request->supplier_id;
            $purchase->user_id = $user->id;
            $purchase->invoice_number = $request->invoice_number;
            $purchase->purchase_date = Carbon::parse($request->purchase_date);
            $purchase->due_date = Carbon::parse($request->due_date);
            $purchase->status = 'invoiced'; 
            $purchase->payment_method = 'credit'; 
            $purchase->payment_status = 'pending';
            $purchase->is_initial_debt = true;
            $purchase->subtotal = $request->grand_total;
            $purchase->tax_amount = 0;
            $purchase->discount_amount = 0;
            $purchase->grand_total = $request->grand_total;
            $purchase->paid_amount = 0;
            $purchase->notes = $request->notes ?: 'Saldo Awal Hutang Manual';
            $purchase->save();

            // ----------------------------------------------------------------
            // JURNAL AKUNTANSI: SALDO AWAL HUTANG (FIXED)
            // ----------------------------------------------------------------
            $payableAcc = AccountingService::getAccountId('payable_account') ?? 28; // Hutang Dagang (Supplier)
            $equityAcc  = AccountingService::getAccountId('default_migration_equity_account') ?? 34; // Modal Disetor (Penyeimbang)

            if (!$payableAcc || !$equityAcc) {
                throw new \Exception("Sistem Gagal: Akun Hutang atau Akun Modal untuk migrasi tidak ditemukan di tabel accounts.");
            }

            AccountingService::log([
                'branch_id'   => $request->branch_id,
                'entry_date'  => $request->purchase_date,
                'description' => "Saldo Awal Hutang: " . $supplier->name,
                'reference'   => $request->invoice_number,
                'source_type' => 'migration_payable',
                'user_id'     => $user->id,
                'items' => [
                    ['account_id' => $equityAcc, 'debit' => $request->grand_total, 'credit' => 0], // DEBIT: Modal / Ekuitas (Penyeimbang)
                    ['account_id' => $payableAcc, 'debit' => 0, 'credit' => $request->grand_total], // KREDIT: Hutang Dagang
                ]
            ]);
            // ----------------------------------------------------------------

            DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'Saldo awal hutang supplier berhasil disimpan dan dijurnal!'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan: ' . $e->getMessage()
            ], 500);
        }
    }

    // --- 5. UPDATE DATA (DENGAN SINKRONISASI JURNAL) ---
    public function update(Request $request, $id)
    {
        $request->validate([
            'invoice_number' => 'required|string|unique:purchases,invoice_number,' . $id,
            'grand_total' => 'required|numeric|min:1',
            'purchase_date' => 'required|date',
            'due_date' => 'required|date',
        ]);

        $user = $request->user();

        DB::beginTransaction();
        try {
            $purchase = Purchase::where('is_initial_debt', true)->findOrFail($id);

            if ($user && $user->role !== 'owner' && $purchase->branch_id !== $user->branch_id) {
                return response()->json(['success' => false, 'message' => 'Akses ditolak: Data hutang ini bukan wewenang cabang Anda.'], 403);
            }

            $oldInvoiceNumber = $purchase->invoice_number; 
            
            $purchase->invoice_number = $request->invoice_number;
            $purchase->purchase_date = Carbon::parse($request->purchase_date);
            $purchase->due_date = Carbon::parse($request->due_date);
            $purchase->subtotal = $request->grand_total;
            $purchase->grand_total = $request->grand_total;
            $purchase->notes = $request->notes;
            $purchase->save();

            // ----------------------------------------------------------------
            // UPDATE JURNAL (FIXED)
            // ----------------------------------------------------------------
            $journal = \App\Models\JournalEntry::where('reference', $oldInvoiceNumber)
                ->where('source_type', 'migration_payable')
                ->first();

            if ($journal) {
                $journal->update([
                    'reference' => $request->invoice_number,
                    'entry_date' => Carbon::parse($request->purchase_date)
                ]);

                $payableAcc = AccountingService::getAccountId('payable_account') ?? 28; 
                $equityAcc  = AccountingService::getAccountId('default_migration_equity_account') ?? 34;

                if (!$payableAcc || !$equityAcc) {
                    throw new \Exception("Sistem Gagal: Akun Hutang atau Modal tidak ditemukan.");
                }

                \App\Models\JournalItem::where('journal_entry_id', $journal->id)
                    ->where('account_id', $equityAcc)
                    ->update(['debit' => $request->grand_total, 'credit' => 0]);
                    
                \App\Models\JournalItem::where('journal_entry_id', $journal->id)
                    ->where('account_id', $payableAcc)
                    ->update(['debit' => 0, 'credit' => $request->grand_total]);
            }
            // ----------------------------------------------------------------

            DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'Perubahan saldo awal hutang dan jurnal berhasil disimpan!'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Gagal memperbarui: ' . $e->getMessage()
            ], 500);
        }
    }

    // --- 6. HAPUS DATA ---
    public function destroy(Request $request, $id)
    {
        $user = $request->user();

        DB::beginTransaction();
        try {
            $purchase = Purchase::where('is_initial_debt', true)->findOrFail($id);

            if ($user && $user->role !== 'owner' && $purchase->branch_id !== $user->branch_id) {
                return response()->json(['success' => false, 'message' => 'Akses ditolak: Data hutang ini bukan wewenang cabang Anda.'], 403);
            }

            $journal = \App\Models\JournalEntry::where('reference', $purchase->invoice_number)
                ->where('source_type', 'migration_payable')
                ->first();
                
            if ($journal) {
                \App\Models\JournalItem::where('journal_entry_id', $journal->id)->delete();
                $journal->delete();
            }

            $purchase->delete();

            DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'Data hutang awal dan jurnal terkait berhasil dihapus.'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus data: ' . $e->getMessage()
            ], 500);
        }
    }

    // --- 7. PREVIEW CSV ---
    public function previewCsv(Request $request)
    {
        $request->validate(['file' => 'required|mimes:csv,txt']);
        $user = $request->user();

        $file = $request->file('file');
        $handle = fopen($file->getPathname(), "r");
        fgetcsv($handle, 1000, ","); // Skip header
        
        $previewData = [];
        $row = 2;

        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $noFaktur = trim($data[0] ?? '');
            $namaSupplier = trim($data[1] ?? '');
            $kodeCabang = trim($data[2] ?? '');
            $nominal = trim($data[3] ?? 0);

            $supplier = Supplier::where('name', 'LIKE', "%$namaSupplier%")->first();
            $branch = Branch::where('code', $kodeCabang)->first();

            $isValid = true;
            $errors = [];

            if (!$supplier) {
                $isValid = false;
                $errors[] = "Supplier '$namaSupplier' tidak ditemukan.";
            }

            if (!$branch) {
                $isValid = false;
                $errors[] = "Cabang '$kodeCabang' tidak valid.";
            } else {
                if ($user && $user->role !== 'owner' && $branch->id !== $user->branch_id) {
                    $isValid = false; 
                    $errors[] = "Akses ditolak untuk memasukkan hutang ke Cabang '$kodeCabang'.";
                }
            }

            if (empty($noFaktur)) {
                $isValid = false;
                $errors[] = "Nomor faktur tidak boleh kosong.";
            }

            if (!is_numeric($nominal) || $nominal <= 0) {
                $isValid = false;
                $errors[] = "Nominal hutang harus angka valid > 0.";
            }

            $previewData[] = [
                'row' => $row,
                'invoice_number' => $noFaktur,
                'supplier_name' => $supplier ? $supplier->name : "N/A",
                'branch_name' => $branch ? $branch->name : "N/A",
                'grand_total' => $nominal,
                'purchase_date' => Carbon::now()->subMonth()->format('Y-m-d'),
                'due_date' => Carbon::now()->format('Y-m-d'),
                'is_valid' => $isValid,
                'errors' => implode(", ", $errors),
                'supplier_id' => $supplier->id ?? null,
                'branch_id' => $branch->id ?? null,
            ];
            $row++;
        }
        fclose($handle);
        return response()->json(['success' => true, 'data' => $previewData]);
    }

    // --- 8. IMPORT MASSAL (STRICT JURNAL) ---
    public function importData(Request $request)
    {
        $items = $request->items;
        $user = $request->user();
        $successCount = 0;

        DB::beginTransaction();
        try {
            $payableAcc = AccountingService::getAccountId('payable_account') ?? 28; 
            $equityAcc  = AccountingService::getAccountId('default_migration_equity_account') ?? 34;

            if (!$payableAcc || !$equityAcc) {
                throw new \Exception("Sistem Gagal: Akun Hutang atau Akun Modal penyeimbang untuk migrasi belum tersedia.");
            }

            foreach ($items as $item) {
                if (!$item['is_valid']) continue;

                if ($user && $user->role !== 'owner' && (int)$item['branch_id'] !== (int)$user->branch_id) {
                    continue; 
                }
                
                Purchase::create([
                    'branch_id' => $item['branch_id'],
                    'supplier_id' => $item['supplier_id'],
                    'user_id' => $user->id,
                    'invoice_number' => $item['invoice_number'],
                    'purchase_date' => $item['purchase_date'],
                    'due_date' => $item['due_date'],
                    'status' => 'invoiced', 
                    'payment_method' => 'credit', 
                    'payment_status' => 'pending',
                    'is_initial_debt' => true,
                    'subtotal' => $item['grand_total'],
                    'tax_amount' => 0,
                    'discount_amount' => 0,
                    'grand_total' => $item['grand_total'],
                    'paid_amount' => 0,
                    'notes' => 'Import Saldo Awal Hutang',
                ]);

                // ----------------------------------------------------------------
                // JURNAL AKUNTANSI: SALDO AWAL HUTANG (CSV)
                // ----------------------------------------------------------------
                AccountingService::log([
                    'branch_id'   => $item['branch_id'],
                    'entry_date'  => $item['purchase_date'],
                    'description' => "Saldo Awal Hutang: " . $item['supplier_name'],
                    'reference'   => $item['invoice_number'],
                    'source_type' => 'migration_payable',
                    'user_id'     => $user->id,
                    'items' => [
                        ['account_id' => $equityAcc, 'debit' => $item['grand_total'], 'credit' => 0], 
                        ['account_id' => $payableAcc, 'debit' => 0, 'credit' => $item['grand_total']], 
                    ]
                ]);
                // ----------------------------------------------------------------
                
                $successCount++;
            }
            DB::commit();
            return response()->json(['success' => true, 'message' => $successCount . ' data hutang berhasil diimport dan dijurnal!']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}