<?php

namespace App\Http\Controllers;

use App\Models\GeneralLedger;
use App\Models\Currency;
use App\Models\Project;
use App\Models\CustomerAccount;
use App\Models\CustomerJournalTemp;
use App\Models\CustomerJournal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CustomerJournalController extends Controller
{
    public function index()
    {
        // Get customer control account
        $customerAccount = GeneralLedger::where('account_name', 'like', '%debtor%')
                                        ->orWhere('account_name', 'like', '%customer%')
                                        ->first();
        
        $currencies = Currency::all();
        $projects = Project::all();
        $customers = CustomerAccount::orderBy('customer_account')->get();
        $tempEntries = CustomerJournalTemp::where('status', 'Pending')->get();

        return view('customerJournal.customer-journal', compact(
            'customerAccount',
            'currencies',
            'projects',
            'customers',
            'tempEntries'
        ));
    }

    public function store(Request $request)
    {
        $request->validate([
            'date' => 'required|date',
            'customer_account_id' => 'required|exists:customer_accounts,id',
            'narration' => 'required|string|max:255',
            'reference' => 'required|string|max:100',
            'currency_id' => 'required|exists:currencies,id',
            'project_id' => 'nullable|exists:projects,id',
            'tr_code' => 'required|in:DR,CR',
            'amount' => 'required|numeric|min:0'
        ]);

        CustomerJournalTemp::create([
            'date' => $request->date,
            'customer_account_id' => $request->customer_account_id,
            'narration' => $request->narration,
            'reference' => $request->reference,
            'currency_id' => $request->currency_id,
            'project_id' => $request->project_id,
            'tr_code' => $request->tr_code,
            'amount' => $request->amount,
            'status' => 'Pending'
        ]);

        return redirect()->route('customer.journal.index')
            ->with('success', 'Journal entry saved successfully!');
    }

    public function update(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:customer_journal_temps,id',
            'date' => 'required|date',
            'customer_account_id' => 'required|exists:customer_accounts,id',
            'narration' => 'required|string|max:255',
            'reference' => 'required|string|max:100',
            'currency_id' => 'required|exists:currencies,id',
            'project_id' => 'nullable|exists:projects,id',
            'tr_code' => 'required|in:DR,CR',
            'amount' => 'required|numeric|min:0'
        ]);

        $entry = CustomerJournalTemp::findOrFail($request->id);

        $entry->update([
            'date' => $request->date,
            'customer_account_id' => $request->customer_account_id,
            'narration' => $request->narration,
            'reference' => $request->reference,
            'currency_id' => $request->currency_id,
            'project_id' => $request->project_id,
            'tr_code' => $request->tr_code,
            'amount' => $request->amount,
        ]);

        return redirect()->route('customer.journal.index')
            ->with('success', 'Journal entry updated successfully!');
    }

    public function destroy($id)
    {
        $entry = CustomerJournalTemp::findOrFail($id);
        $entry->delete();

        return redirect()->route('customer.journal.index')
            ->with('success', 'Entry deleted successfully!');
    }

    public function process()
    {
        DB::transaction(function () {
            $tempEntries = CustomerJournalTemp::where('status', 'Pending')->get();

            foreach ($tempEntries as $entry) {
                // Create permanent journal entry
                CustomerJournal::create([
                    'date' => $entry->date,
                    'customer_account_id' => $entry->customer_account_id,
                    'narration' => $entry->narration,
                    'reference' => $entry->reference,
                    'currency_id' => $entry->currency_id,
                    'project_id' => $entry->project_id,
                    'tr_code' => $entry->tr_code,
                    'amount' => $entry->amount
                ]);

                // Delete temporary entry
                $entry->delete();
            }
        });

        return redirect()->route('customer.journal.index')
            ->with('success', 'Journal processed successfully!');
    }

    public function processSingle($id)
    {
        DB::transaction(function () use ($id) {
            $entry = CustomerJournalTemp::findOrFail($id);

            // Create permanent journal entry
            CustomerJournal::create([
                'date' => $entry->date,
                'customer_account_id' => $entry->customer_account_id,
                'narration' => $entry->narration,
                'reference' => $entry->reference,
                'currency_id' => $entry->currency_id,
                'project_id' => $entry->project_id,
                'tr_code' => $entry->tr_code,
                'amount' => $entry->amount
            ]);

            // Delete temporary entry
            $entry->delete();
        });

        return redirect()->route('customer.journal.index')
            ->with('success', 'Single journal entry processed successfully!');
    }
}
