<?php
namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\User\Member;
use App\Models\User\Product;
use App\Models\User\Sales;
use App\Models\User\SalesItem;
use App\Models\User\Line;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SaleController extends Controller
{
    public function create()
    {
        return view('user.sales.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('line_name', 'like', "{$q}%")
              ->where('type', 'Customer')
            ->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 searchCustomers(Request $request)
    {
        $q = (string) $request->query('q', '');
        if ($q === '') {
            return response()->json([]);
        }

        $userId = session('user_id');

        $results = Member::where('user_id', $userId)
      
            ->where(function ($b) use ($q) {
                
                $b->where('name', 'like', "{$q}%")
                  ->where('type', 'Customer');
                    // ->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([
//             'sales_date'    => 'required|date',
//             'line_id'          => 'required|integer',
//             'customer_id'      => 'required|integer',
//             'customer_name'    => 'required|string',
//             'customer_address' => 'nullable|string',
//             'customer_phone'   => 'nullable|string',
//             'lines'            => 'required|string',
//             'total_amount'     => 'required|numeric|min:0',
//             'paid_amount'      => 'nullable|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 = Sales::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 ------- */
//             $sales = Sales::create([
                
//                 'user_id'          => $userId,
//                 'customer_id'      => $v['customer_id'],
//                 'member_id'        => $v['customer_id'],
//                 'customer_name'    => $v['customer_name'],
//                 'customer_contact' => $v['customer_phone'] ?? null,
//                 'customer_address' => $v['customer_address'] ?? null,

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

//                 'items_id'         => $uniqueItemsId,

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

//             /* ------- Save sales 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);

//         SalesItem::create([
//             'user_id'       => $userId,
//             'items_id'      => $sales->id,   // <-- REAL ID
//             'product_id'    => $productId,
//             'line_id'       => $v['line_id'],
//             'line_name'     => $lineName,
//             'product_name'  => $productName,
//             'unit'          => $l['unit'] ?? null,
//             'quantity'      => $qty,
//             'rate'          => $rate,
//             'amount'        => $amount,
//             'sales_date' => $v['sales_date'],
//         ]);
//     }

//     DB::commit();

// } catch (\Throwable $e) {

//     dd([
//         'error' => $e->getMessage(),
//         'line' => $e->getLine(),
//         'file' => $e->getFile(),
//         'item' => $l ?? 'no item'
//     ]);
// }
//             return redirect()
//                 ->route('user.sales.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 save(Request $request)
{
    $v = $request->validate([
        'sales_date'      => 'required|date',
        'line_id'         => 'required|integer',
        'customer_id'     => 'required|integer',
        'customer_name'   => 'required|string',
        'customer_address'=> 'nullable|string',
        'customer_phone'  => 'nullable|string',
        'lines'           => 'required|json',   // FIXED
        'total_amount'    => 'required|numeric|min:0',
        'paid_amount'     => 'nullable|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.']);
    }

    // AUTO INCREMENT ITEMS_ID
    $lastId = Sales::max('items_id');
    $uniqueItemsId = $lastId ? $lastId + 1 : 1;

    // GET 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 SALES HEADER
        $sales = Sales::create([
            'user_id'          => $userId,
            'customer_id'      => $v['customer_id'],
            'member_id'        => $v['customer_id'],
            'customer_name'    => $v['customer_name'],
            'customer_contact' => $v['customer_phone'],
            'customer_address' => $v['customer_address'],
            'line_id'          => $v['line_id'],
            'line_name'        => $lineName,
            'items_id'         => $uniqueItemsId,   // SAME ID
            'date'             => $v['sales_date'],
            'total_amount'     => $v['total_amount'],
            'paid_amount'      => $v['paid_amount'] ?? 0,
        ]);

        // SAVE ITEMS
        foreach ($lines as $l) {

            $productId   = $l['product_id'] ?? null;
            $productName = $l['product_name'] ?? '';
            $qty         = $l['quantity'] ?? 0;
            $rate        = $l['price'] ?? 0;
            $amount      = $l['amount'] ?? ($qty * $rate);

            SalesItem::create([
                'user_id'      => $userId,
                'items_id'     => $sales->id,  // FIXED
                'customer_id'  => $v['customer_id'],
                'product_id'   => $productId,
                'line_id'      => $v['line_id'],
                'line_name'    => $lineName,
                'product_name' => $productName,
                'unit'         => $l['unit'] ?? null,
                'quantity'     => $qty,
                'rate'         => $rate,
                'amount'       => $amount,
                'sales_date'   => $v['sales_date'],
            ]);
        }

        DB::commit();

        return redirect()
            ->route('user.sales.create')
            ->with('success', 'Sales saved successfully.');

    } catch (\Throwable $e) {

        DB::rollBack();

        dd([
            'error' => $e->getMessage(),
            'line'  => $e->getLine(),
            'file'  => $e->getFile(),
            'item'  => $l ?? null
        ]);
    }
}


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

    $data = Sales::with('items')
        ->whereDate('date', $today)
        ->orderBy('id', 'DESC')
        ->get()
        ->map(function ($p) {
            return [
                'id' => $p->id,
                'line' => $p->line_name,
                'customer' => $p->customer_name,
                'total_amount' => $p->total_amount,
                'paid_amount' => $p->paid_amount ?? 0,
                'time' => $p->created_at->format('h:i A'),

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

    return response()->json([
        'data' => $data
    ]);
}
public function softDelete(Sales $sale)
{
    // If sale has related items
    $sale->items()->delete();   // soft delete sale items (if relation exists)

    $sale->delete();            // soft delete sale

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

}
