<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\PurchaseOrder;
use App\Purchaser;
use Carbon\Carbon;

class PurchaseRegisterReportController extends Controller
{
    protected string $module = 'Reports Management';

    public function __construct()
    {
        $module = $this->module;
        $this->middleware("permission:$module Purchase Register")->only(['index']);
    }
    /**
     * Show the Purchase Register report with filters.
     */
    public function index(Request $request)
    {
        // ── Default date range: current month ──
        $fromDate    = $request->input('from_date',    Carbon::now()->startOfMonth()->toDateString());
        $toDate      = $request->input('to_date',      Carbon::now()->toDateString());
        $purchaserId = $request->input('purchaser_id', null);

        // ── All purchasers for the dropdown ──
        $purchasers = Purchaser::orderBy('purchaser_name')->get();

        $selectedPurchaser = $purchaserId
            ? Purchaser::find($purchaserId)
            : null;

        $reportData = null;

        if ($request->isMethod('get') && ($request->has('from_date') || $request->has('to_date') || $request->has('purchaser_id'))) {
            $reportData = $this->buildReport($fromDate, $toDate, $purchaserId);
        }

        return view('reports.purchase_register', compact(
            'fromDate', 'toDate', 'purchaserId',
            'purchasers', 'selectedPurchaser',
            'reportData'
        ));
    }

    /**
     * Print view for the Purchase Register.
     */
    public function print(Request $request)
    {
        $fromDate    = $request->input('from_date');
        $toDate      = $request->input('to_date');
        $purchaserId = $request->input('purchaser_id');

        $selectedPurchaser = $purchaserId
            ? Purchaser::find($purchaserId)
            : null;

        $reportData = $this->buildReport($fromDate, $toDate, $purchaserId);

        return view('reports.purchase_register_print_view', compact(
            'fromDate', 'toDate',
            'selectedPurchaser',
            'reportData'
        ));
    }

    // ──────────────────────────────────────────────
    //  Core report builder
    // ──────────────────────────────────────────────
    private function buildReport($fromDate, $toDate, $purchaserId = null)
    {
        // ── Base query ──
        $query = PurchaseOrder::with(['purchaser', 'Purchasedetails'])
            ->whereBetween('order_date', [$fromDate, $toDate])
            ->orderBy('purchaser_id')
            ->orderBy('order_date');

        if ($purchaserId) {
            $query->where('purchaser_id', $purchaserId);
        }

        $orders = $query->get();

        // ── Build grouped structure ──
        $departments = [];   // keyed by purchaser_name (English)

        $grandBori    = 0;
        $grandWeight  = 0;
        $grandAmount  = 0;
        $grandOrders  = 0;

        foreach ($orders as $order) {
            $purchaserName = $order->purchaser
                ? $order->purchaser->purchaser_name
                : 'Unknown';

            $urduName = $order->purchaser
                ? ($order->purchaser->purchaser_name_urdu ?: $purchaserName)
                : $purchaserName;

            // Initialise group
            if (!isset($departments[$purchaserName])) {
                $departments[$purchaserName] = [
                    'urdu_name'  => $urduName,
                    'orders'     => [],
                    'subBori'    => 0,
                    'subWeight'  => 0,
                    'subAmount'  => 0,
                    'subOrders'  => 0,
                ];
            }

            // ── Build detail rows from purchase_order_details ──
            $detailRows  = [];
            $orderBori   = 0;
            $orderWeight = 0;
            $orderAmount = 0;   // sum of detail amounts only (excl. charges)

            foreach ($order->Purchasedetails as $detail) {
                $detailRows[] = [
                    'name'   => $detail->name   ?? ($detail->proCateChild->name ?? '—'),
                    'marka'  => $detail->marka  ?? '',
                    'bori'   => $detail->bori   ?? 0,
                    'weight' => $detail->weight ?? 0,
                    'rate'   => $detail->rate   ?? 0,
                    'amount' => $detail->amount ?? 0,
                ];
                $orderBori   += $detail->bori   ?? 0;
                $orderWeight += $detail->weight ?? 0;
                $orderAmount += $detail->amount ?? 0;
            }

            // Grand total for this order (includes charges stored on PO)
            $orderGrandTotal = $order->grand_total ?? ($orderAmount + ($order->labour_charges ?? 0));

            $departments[$purchaserName]['orders'][] = [
                'po_number'      => $order->po_number,
                'order_date'     => Carbon::parse($order->order_date)->format('d/m/y'),
                'details'        => $detailRows,
                'total_bori'     => $orderBori,
                'total_weight'   => $orderWeight,
                'total_amount'   => $orderAmount,
                'labour_charges' => $order->labour_charges ?? 0,
                'grand_total'    => $orderGrandTotal,
            ];

            // Accumulate purchaser sub-totals
            $departments[$purchaserName]['subBori']   += $orderBori;
            $departments[$purchaserName]['subWeight']  += $orderWeight;
            $departments[$purchaserName]['subAmount']  += $orderGrandTotal;
            $departments[$purchaserName]['subOrders']  += 1;

            // Accumulate grand totals
            $grandBori   += $orderBori;
            $grandWeight += $orderWeight;
            $grandAmount += $orderGrandTotal;
            $grandOrders += 1;
        }

        return [
            'purchasers'   => $departments,
            'grandBori'    => $grandBori,
            'grandWeight'  => $grandWeight,
            'grandAmount'  => $grandAmount,
            'grandOrders'  => $grandOrders,
        ];
    }
}