<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use App\Models\CustomerCategory;
use App\Models\SalesRep;
use App\Models\Area;
use App\Models\CustomerAccount;
use App\Models\HomeCurrency;
use App\Models\Currency;
use App\Models\Ageing;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AccountsController extends Controller
{
    /**
     * Show the "Add Customer Account" form and list existing accounts.
     */
    public function create_customer_account()
    {
        try {
            $customerCategories = CustomerCategory::all();
            $salesReps          = SalesRep::all();
            $areas              = Area::all();
            $ageings            = Ageing::all();

            // Grab the HomeCurrency row (which has a currency_id column)
            $homeCurrencyRow = HomeCurrency::first();

            // Extract currency_id (if any)
            $homeCurrencyId = $homeCurrencyRow->currency_id ?? null;

            // Look up its name, fallback to 'USD' if missing
            if ($homeCurrencyId) {
                $homeCurrencyModel = Currency::find($homeCurrencyId);
                $defaultHomeCurrencyName = $homeCurrencyModel
                    ? $homeCurrencyModel->name
                    : 'USD';
            } else {
                $defaultHomeCurrencyName = 'USD';
            }

            // Build the list of foreign currencies by excluding the home-currency ID
            $foreignCurrencies = $homeCurrencyId
                ? Currency::where('id', '!=', $homeCurrencyId)->get()
                : Currency::all();

            // Eager-load for the table below
            $customerAccounts = CustomerAccount::with([
                'category',
                'salesRep',
                'ageAnalysis',
                'area',
                'foreignCurrency',
            ])->get();

            return view(
                'maintanance.customers.create_customer_account',
                compact(
                    'customerCategories',
                    'salesReps',
                    'areas',
                    'customerAccounts',
                    'foreignCurrencies',
                    'defaultHomeCurrencyName',
                    'ageings'
                )
            );
        } catch (Exception $e) {
            Log::error('Error loading customer accounts page: ' . $e->getMessage());
            return redirect()->route('home')->with('error', 'Failed to load customer accounts page: ' . $e->getMessage());
        }
    }

    /**
     * Get terms for a specific ageing analysis
     */
    public function get_ageing_terms($id)
    {
        try {
            $ageing = Ageing::findOrFail($id);
            
            $terms = [
                $ageing->custom_age_1,
                $ageing->custom_age_2,
                $ageing->custom_age_3,
                $ageing->custom_age_4,
                $ageing->custom_age_5,
                $ageing->custom_age_6,
                $ageing->custom_age_7
            ];
            
            // Filter out empty values
            $terms = array_filter($terms);
            
            return response()->json([
                'success' => true,
                'terms' => $terms
            ]);
        } catch (Exception $e) {
            Log::error('Error fetching ageing terms: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch terms'
            ]);
        }
    }

    /**
     * Store a newly created customer account.
     */
    public function store_customer_account(Request $request)
    {
        try {
            $validated = $request->validate([
                'customer_code'       => 'required|string|max:255|unique:customer_accounts,customer_code',
                'customer_account'    => 'required|string|max:255',
                'contact_person'      => 'required|string|max:255',
                'contact_1'           => 'required|string|max:50',
                'contact_2'           => 'nullable|string|max:50',
                'email'               => 'nullable|email|max:255',
                'address'             => 'nullable|string',
                'category_id'         => 'nullable|integer|exists:customer_categories,id',
                'sales_rep_id'        => 'nullable|integer|exists:sales_reps,id',
                'age_analysis_id'     => 'nullable|integer|exists:ageings,id',
                'terms'               => 'nullable|string|max:255',
                'area_id'             => 'nullable|integer|exists:areas,id',
                'vat'                 => 'nullable|string|max:255',
                'tin'                 => 'nullable|string|max:255',
                'city'                => 'nullable|string|max:255',
                'province'            => 'nullable|string|max:255',
                'is_foreign_currency' => 'nullable|boolean',
                'foreign_currency_id' => 'nullable|integer|exists:currencies,id',
            ]);

            // Checkbox handling
            $validated['is_foreign_currency'] = $request->has('is_foreign_currency') ? 1 : 0;
            if (!$validated['is_foreign_currency']) {
                $validated['foreign_currency_id'] = null;
            }
            
            // Set account_type to empty string as required by database
            $validated['account_type'] = '';

            DB::beginTransaction();
            
            CustomerAccount::create($validated);
            
            DB::commit();

            return redirect()
                ->route('customer.accounts.create')
                ->with('success', 'Customer account created successfully.');
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('Error storing customer account: ' . $e->getMessage());
            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'An error occurred while creating the customer account: ' . $e->getMessage());
        }
    }

    /**
     * Update an existing customer account.
     */
    public function edit_customer_account(Request $request)
    {
        try {
            $validated = $request->validate([
                'id'                  => 'required|integer|exists:customer_accounts,id',
                'customer_code'       => 'required|string|max:255|unique:customer_accounts,customer_code,' . $request->id,
                'customer_account'    => 'required|string|max:255',
                'contact_person'      => 'required|string|max:255',
                'contact_1'           => 'required|string|max:50',
                'contact_2'           => 'nullable|string|max:50',
                'email'               => 'nullable|email|max:255',
                'address'             => 'nullable|string',
                'category_id'         => 'nullable|integer|exists:customer_categories,id',
                'sales_rep_id'        => 'nullable|integer|exists:sales_reps,id',
                'age_analysis_id'     => 'nullable|integer|exists:ageings,id',
                'terms'               => 'nullable|string|max:255',
                'area_id'             => 'nullable|integer|exists:areas,id',
                'vat'                 => 'nullable|string|max:255',
                'tin'                 => 'nullable|string|max:255',
                'city'                => 'nullable|string|max:255',
                'province'            => 'nullable|string|max:255',
                'is_foreign_currency' => 'nullable|boolean',
                'foreign_currency_id' => 'nullable|integer|exists:currencies,id',
            ]);

            // Checkbox handling
            $validated['is_foreign_currency'] = $request->has('is_foreign_currency') ? 1 : 0;
            if (!$validated['is_foreign_currency']) {
                $validated['foreign_currency_id'] = null;
            }

            DB::beginTransaction();
            
            // Find the account and update it
            $account = CustomerAccount::findOrFail($validated['id']);
            $account->update($validated);
            
            DB::commit();

            return redirect()
                ->route('customer.accounts.create')
                ->with('success', 'Customer account updated successfully.');
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('Error updating customer account: ' . $e->getMessage());
            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'An error occurred while updating the customer account: ' . $e->getMessage());
        }
    }

    /**
     * Delete a customer account.
     */
    public function delete_customer_account($id)
    {
        try {
            DB::beginTransaction();
            
            $account = CustomerAccount::findOrFail($id);
            $account->delete();
            
            DB::commit();

            return redirect()
                ->route('customer.accounts.create')
                ->with('success', 'Customer account deleted successfully.');
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('Error deleting customer account: ' . $e->getMessage());
            return redirect()
                ->route('customer.accounts.create')
                ->with('error', 'An error occurred while deleting the customer account: ' . $e->getMessage());
        }
    }
}