<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\User\Purchase;
use App\Models\User\PurchaseItem;

use App\Models\User\Sales;
use App\Models\SaleItem;

use App\Models\User\Product;

class ReportController extends Controller
{
    // -----------------------------------------------------------
    // MAIN MENU
    // -----------------------------------------------------------
    public function index()
    {
        return view('user.reports.index');
    }

    // -----------------------------------------------------------
    // PURCHASE REPORT LIST PAGE
    // -----------------------------------------------------------
    public function purchaseReport()
    {
        $purchases = Purchase::with('items')->latest()->get();

        return view('user.reports.purchases', compact('purchases'));
    }

    // -----------------------------------------------------------
    // SALES REPORT LIST PAGE
    // -----------------------------------------------------------
    public function salesReport()
    {
        $sales = Sales::with('items')->latest()->get();

        return view('user.reports.sales', compact('sales'));
    }
public function dailysalesReport()
    {
        $sales = Sales::with('items')->latest()->get();

        return view('user.reports.dailysalesReport', compact('sales'));
    }
    public function dailypurchaseReport()
    {
        $sales = Sales::with('items')->latest()->get();

        return view('user.reports.dailypurchaseReport', compact('sales'));
    }
    // -----------------------------------------------------------
    // STOCK REPORT
    // -----------------------------------------------------------
    public function stockReport()
    {
        $products = Product::with(['purchaseItems', 'saleItems'])->get();

        return view('user.reports.stock', compact('products'));
    }

    // -----------------------------------------------------------
    // SEARCH PURCHASE BY DATE (AJAX)
    // -----------------------------------------------------------
    public function searchPurchase(Request $request)
    {
        $date = $request->query('date');

        if (!$date) {
            return response()->json(['data' => []]);
        }

        $userId = session('user_id');

        $data = Purchase::with('items')
            ->where('user_id', $userId)
            ->whereDate('date', $date)
            ->orderBy('id', 'DESC')
            ->get()
            ->map(function ($p) {
                return [
                    'id' => $p->id,
                    'line' => $p->line_name,
                    'supplier_name' => $p->supplier_name,
                    'amount' => $p->total_amount,
                    'time' => $p->created_at->format('h:i A'),
                ];
            });

        return response()->json(['data' => $data]);
    }

    // -----------------------------------------------------------
    // SEARCH SALES BY DATE (AJAX)
    // -----------------------------------------------------------
    public function searchSales(Request $request)
    {
        $date = $request->query('date');

        if (!$date) {
            return response()->json(['data' => []]);
        }

        $userId = session('user_id');

        $data = Sales::with('items')
            ->where('user_id', $userId)
            ->whereDate('date', $date)
            ->orderBy('id', 'DESC')
            ->get()
            ->map(function ($s) {
                return [
                    'id' => $s->id,
                    'line' => $s->line_name,
                    'customer_name' => $s->customer_name,
                    'amount' => $s->total_amount,
                    'time' => $s->created_at->format('h:i A'),
                ];
            });

        return response()->json(['data' => $data]);
    }

    // -----------------------------------------------------------
    // SHOW PURCHASE BILL
    // -----------------------------------------------------------
  public function showPurchase(Request $request, $id)
{
    $purchase = Purchase::with('items.product')
        ->where('id', $id)
        ->firstOrFail();

    return view('user.reports.show', [
        'mode' => 'purchase',
        'bill' => $purchase,
        'items' => $purchase->items
    ]);
}

public function showSales(Request $request, $id)
{
    $sales = Sales::with('items.product')
        ->where('id', $id)
        ->firstOrFail();

    return view('user.reports.show', [
        'mode' => 'sales',
        'bill' => $sales,
        'items' => $sales->items
    ]);
}
public function dailySalesSearch(Request $request)
{
    $search = $request->search ?? '';

    $sales = Sales::with('items')
        ->whereDate('created_at', today())
        ->where(function ($q) use ($search) {
            $q->where('customer_name', 'like', "%$search%")
              ->orWhere('customer_contact', 'like', "%$search%")
              ->orWhereHas('items', function ($q2) use ($search) {
                  $q2->where('product_name', 'like', "%$search%");
              });
        })
        ->get();

    $result = [];

    foreach ($sales as $sale) {
        $row = [
            "customer_name" => $sale->customer_name,
            "customer_contact" => $sale->customer_contact,
            "total_bill" => number_format($sale->total_amount, 2),
            "paid" => number_format($sale->paid_amount, 2),
            "time" => $sale->created_at->format('h:i A'),
            "items" => []
        ];

        foreach ($sale->items as $item) {
            $row['items'][] = [
                "product_name" => $item->product_name,
                "quantity" => $item->quantity,
                "rate" => $item->rate,
                "amount" => $item->amount,
                "time" => $item->created_at->format('h:i A')
            ];
        }

        $result[] = $row;
    }

    return response()->json([
        "data" => $result
    ]);
}

public function todayPurchases(Request $request)
{
    $search = $request->search ?? '';

    $purchases = Purchase::with('items')
        ->whereDate('created_at', today())
        ->where(function ($q) use ($search) {
            $q->where('supplier_name', 'like', "%$search%")
              ->orWhere('supplier_contact', 'like', "%$search%")
              ->orWhereHas('items', function ($q2) use ($search) {
                  $q2->where('product_name', 'like', "%$search%");
              });
        })
        ->get();

    $result = [];

    foreach ($purchases as $p) {
        $row = [
            "supplier_name"   => $p->supplier_name,
            "supplier_contact" => $p->supplier_contact,
            "total_bill"      => number_format($p->total_amount, 2),
            "paid"            => number_format($p->paid_amount, 2),
            "time"            => $p->created_at->format('h:i A'),
            "items" => []
        ];

        foreach ($p->items as $item) {
            $row['items'][] = [
                "product_name" => $item->product_name,
                "quantity"     => $item->quantity,
                "rate"         => $item->rate,
                "amount"       => $item->amount,
                "time"         => $item->created_at->format('h:i A'),
            ];
        }

        $result[] = $row;
    }

    return response()->json([
        "data" => $result
    ]);
}
public function purchaseLedger()
{
    return view('user.reports.purchaseLedger');
}

public function purchaseLedgerSearch(Request $request)
{
    $search = $request->search ?? '';

    $purchases = Purchase::with('items')
        ->where(function ($q) use ($search) {
            $q->where('supplier_name', 'like', "%$search%")
              ->orWhere('supplier_contact', 'like', "%$search%");
        })
        ->get()
        ->groupBy('supplier_id');  // group by supplier

    $supplier_data = [];
    $grand_total = 0;
    $grand_paid = 0;
    $grand_balance = 0;

    foreach ($purchases as $supplierId => $rows) {

        $total = $rows->sum('total_amount');
        $paid = $rows->sum('paid_amount');
        $balance = $total - $paid;

        // add to grand totals
        $grand_total += $total;
        $grand_paid += $paid;
        $grand_balance += $balance;

        $supplierInfo = [
            "supplier_id" => $supplierId,
            "supplier" => $rows->first()->supplier_name,
            "contact" => $rows->first()->supplier_contact,
            "total" => number_format($total, 2),
            "paid" => number_format($paid, 2),
            "balance" => number_format($balance, 2),
            "records" => []
        ];

        foreach ($rows as $p) {
            $supplierInfo["records"][] = [
                "date" => $p->date,
                "bill_no" => $p->id,
                "amount" => number_format($p->total_amount, 2),
                "paid" => number_format($p->paid_amount, 2),
                "balance" => number_format($p->total_amount - $p->paid_amount, 2),
            ];
        }

        $supplier_data[] = $supplierInfo;
    }

    return response()->json([
        'summary' => [
            'total'   => number_format($grand_total, 2),
            'paid'    => number_format($grand_paid, 2),
            'balance' => number_format($grand_balance, 2),
        ],
        'data' => $supplier_data
    ]);
}

public function salesLedger()
{
    return view('user.reports.salesledger');
}

public function salesLedgerSearch(Request $request)
{
    $search = $request->search ?? '';

    $sales = Sales::with('items')
        ->where(function ($q) use ($search) {
            $q->where('customer_name', 'like', "%$search%")
              ->orWhere('customer_contact', 'like', "%$search%");
        })
        ->get()
        ->groupBy('customer_id');  // Group by unique ID

    $customer_data = [];
    $grand_total = 0;
    $grand_paid = 0;
    $grand_balance = 0;

    foreach ($sales as $custId => $rows) {

        $total = $rows->sum('total_amount');
        $paid = $rows->sum('paid_amount');
        $balance = $total - $paid;

        // Add to overall total
        $grand_total += $total;
        $grand_paid += $paid;
        $grand_balance += $balance;

        $customerInfo = [
            "customer_id" => $custId,
            "customer" => $rows->first()->customer_name,
            "contact" => $rows->first()->customer_contact,
            "total" => number_format($total, 2),
            "paid" => number_format($paid, 2),
            "balance" => number_format($balance, 2),
            "records" => []
        ];

        foreach ($rows as $s) {
            $customerInfo["records"][] = [
                "date" => $s->date,
                "bill_no" => $s->id,
                "amount" => number_format($s->total_amount, 2),
                "paid" => number_format($s->paid_amount, 2),
                "balance" => number_format($s->total_amount - $s->paid_amount, 2),
            ];
        }

        $customer_data[] = $customerInfo;
    }

    return response()->json([
        'summary' => [
            'total'   => number_format($grand_total, 2),
            'paid'    => number_format($grand_paid, 2),
            'balance' => number_format($grand_balance, 2),
        ],
        'data' => $customer_data
    ]);
}

}
