<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Models\User\Line;
use App\Models\User\Member;
use App\Models\User\Product;
use App\Models\User\Purchase;
use App\Models\User\PurchaseItem;

class PurchaseController extends Controller
{
    public function create()
    {
        return view('user.purchase.create');
    }

    /* --------------------------------------------------------------------------
     * SEARCH LINES
     * -------------------------------------------------------------------------- */
    public function searchLines(Request $request)
    {
        $q = trim($request->query('q', ''));

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

        $userId = session('user_id');

        $results = Line::where('user_id', $userId)
            ->where('type', 'Supplier')
            ->where('line_name', 'like', "{$q}%")
            
            ->limit(15)
            ->get(['line_id', 'line_name'])
            ->map(function ($r) {
                return [
                    'id'        => $r->line_id,
                    'line_name' => $r->line_name,
                ];
            });

        return response()->json($results);
    }

    /* --------------------------------------------------------------------------
     * SEARCH SUPPLIERS
     * -------------------------------------------------------------------------- */
    public function searchSuppliers(Request $request)
    {
        $q = (string) $request->query('q', '');
        if ($q === '') {
            return response()->json([]);
        }

        $userId = session('user_id');

        $results = Member::where('user_id', $userId)
            ->where('type', 'Supplier')
            ->where(function ($b) use ($q) {
                $b->where('name', 'like', "{$q}%");
                    // ->orWhere('phone', 'like', "%{$q}%")
                    // ->orWhere('address', 'like', "%{$q}%");
            })
            ->limit(15)
            ->get(['id', 'name', 'address', 'phone'])
            ->map(function ($r) {
                return [
                    'member_id'   => $r->id,
                    'member_name' => $r->name,
                    'id'          => $r->id,
                    'name'        => $r->name,
                    'address'     => $r->address ?? '',
                    'phone'       => $r->phone ?? '',
                ];
            });

        return response()->json($results);
    }

    /* --------------------------------------------------------------------------
     * SEARCH PRODUCTS
     * -------------------------------------------------------------------------- */
    public function searchProducts(Request $request)
    {
        $q = (string) $request->query('q', '');
        if ($q === '') {
            return response()->json([]);
        }

        $userId = session('user_id');

        $results = Product::where('user_id', $userId)
            ->where('product_name', 'like', "{$q}%")
            ->limit(20)
            ->get(['id', 'product_name',  'price'])
            ->map(function ($r) {
                return [
                    'product_id'   => $r->id,
                    'product_name' => $r->product_name,
                    'id'           => $r->id,
                    'name'         => $r->product_name,
                
                    'price'        => $r->price ?? 0,
                ];
            });

        return response()->json($results);
    }

    /* --------------------------------------------------------------------------
     * SAVE PURCHASE + ITEMS
     * -------------------------------------------------------------------------- */
    public function save(Request $request)
    {
      
        $v = $request->validate([
            'purchase_date'    => 'required|date',
            'line_id'          => 'required|integer',
            'supplier_id'      => 'required|integer',
            'supplier_name'    => 'required|string',
            'supplier_address' => 'nullable|string',
            'supplier_phone'   => 'nullable|string',
            'lines'            => 'required|string',
            'total_amount'     => 'required|numeric|min:0',
        
        ]);

        $userId = session('user_id');

        $lines = json_decode($request->lines, true);

        if (!is_array($lines) || count($lines) === 0) {
            return back()->withErrors(['lines' => 'No items found.']);
        }

        /* ------- UNIQUE NUMERIC ITEMS ID ------- */
$lastId = Purchase::max('items_id');  
$nextId = $lastId ? $lastId + 1 : 1;
$uniqueItemsId = $nextId;


        /* ------- Fetch Line Name ------- */
        $line = Line::where('user_id', $userId)
                    ->where('line_id', $v['line_id'])
                    ->first();

        $lineName = $line ? $line->line_name : null;

        DB::beginTransaction();

        try {

            /* ------- Save Purchase Header ------- */
            $purchase = Purchase::create([
                
                'user_id'          => $userId,
                'supplier_id'      => $v['supplier_id'],
                'member_id'        => $v['supplier_id'],
                'supplier_name'    => $v['supplier_name'],
                'supplier_contact' => $v['supplier_phone'] ?? null,
                'supplier_address' => $v['supplier_address'] ?? null,

                'line_id'          => $v['line_id'],
                'line_name'        => $lineName,

                'items_id'         => $uniqueItemsId,

                'date'             => $v['purchase_date'],
                'total_amount'     => $v['total_amount'],
                'paid_amount'      => $v['paid_amount'] ?? 0,
            ]);

            /* ------- Save Purchase Items ------- */
           try {

    foreach ($lines as $l) {

        // DEBUG INSIDE LOOP
        // This will show exactly which item breaks
        // Remove after testing
        // dd($l);

        $productId   = $l['product_id'] ?? null;
        $productName = $l['product_name'] ?? '';
        $qty         = $l['quantity'] ?? 0;
        $rate        = $l['price'] ?? 0;
        $amount      = $l['amount'] ?? ($qty * $rate);
        $supAmount   = $l['sup_amount'] ?? 0;
        $commission  = $l['comm'] ?? 0;
        $comAmount   = $l['com_amount'] ?? 0;

        PurchaseItem::create([
            'user_id'       => $userId,
            'supplier_id'  => $v['supplier_id'],
            'items_id'      => $purchase->id,   // <-- REAL ID
            'product_id'    => $productId,
            'line_id'       => $v['line_id'],
            'line_name'     => $lineName,
            'product_name'  => $productName,
            'quantity'      => $qty,
            'rate'          => $rate,
            'sup_amount'    => $supAmount,
            'comm'    => $commission,
            'com_amount'    => $comAmount,
            'amount'        => $amount,
            'lastCoAmount'  => $l['lastCoAmount'] ?? 0,
            'purchase_date' => $v['purchase_date'],
        ]);
    }

    DB::commit();

} catch (\Throwable $e) {

    dd([
        'error' => $e->getMessage(),
        'line' => $e->getLine(),
        'file' => $e->getFile(),
        'item' => $l ?? 'no item'
    ]);
}
            return redirect()
                ->route('user.purchase.create')
                ->with('success', 'Purchase saved successfully.');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->withErrors(['error' => 'An error occurred while saving the purchase. Please try again.']);
        }

    }

   public function todayData()
{
    $today = now()->toDateString();

    $data = Purchase::with('items')
        ->whereDate('date', $today) // IMPORTANT FIX
        ->orderBy('id', 'DESC')
        ->get()
        ->map(function ($p) {
            return [
                'id' => $p->id,
                'line' => $p->line_name,
                'supplier' => $p->supplier_name,
                'total_amount' => $p->total_amount,
                'paid_amount' => $p->paid_amount,
                'time' => $p->created_at->format('h:i A'),

                'items' => $p->items->map(function ($i) {
                    return [
                        'price' => $i->rate,
                        'product_name' => $i->product_name,
                        'qty' => $i->quantity,
                        'lastCoAmount' => $i->lastCoAmount,
                        'total' => $i->amount,

                    ];
                })
            ];
        });

    return response()->json(['data' => $data]);
}
public function softDelete(Purchase $purchase)
{
    // Soft delete related items
    $purchase->items()->delete();

    // Soft delete purchase
    $purchase->delete();

    return response()->json([
        'status' => true,
        'message' => 'Purchase deleted successfully'
    ], 200);
}


}
