<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\DirectSales;
use Carbon\Carbon;
use Illuminate\Http\Request;

class DirectSalesController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        // Get the filter from the request
        $filterSql = DirectSales::query()->with('Customer');

        if ($request->has('date_range')) {
            $dates = explode(' - ', $request->input('date_range'));

            try {
                $startDate = Carbon::createFromFormat('Y-m-d', trim($dates[0]))->startOfDay();
                $endDate = Carbon::createFromFormat('Y-m-d', trim($dates[1]))->endOfDay();

                // Apply date range filter
                $filterSql->whereBetween('direct_date_time', [$startDate, $endDate]);
            } catch (\Exception $e) {
                return response()->json(['error' => 'Invalid date format: ' . $e->getMessage()], 400);
            }
        }

        // Fetch paginated sales records
        $sales = $filterSql->orderBy('direct_date_time', 'desc')->paginate(10);

        // Calculate totals
        $totalProfit = $sales->sum('direct_profit');
        $totalSale = $sales->sum('direct_sold_quantity');
        $totalAmount = $sales->sum(fn($sale) => $sale->direct_sell_price * $sale->direct_sold_quantity);

        // Check if request is AJAX
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'sales' => $sales,
                'totalProfit' => number_format($totalProfit, 2),
                'totalSale' => $totalSale,
                'totalAmount' => number_format($totalAmount, 2),
            ], 200);
        }

        return view('direct_sell.report', compact('sales', 'totalProfit', 'totalSale', 'totalAmount'));
    }




    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {

        $transactions = DirectSales::all();

        // // If it's an AJAX request with a date range
        // if ($request->ajax() && $request->has('date_range')) {
        //     $dates = explode(' - ', $request->date_range);
        //     $startDate = Carbon::parse($dates[0])->startOfDay();
        //     $endDate = Carbon::parse($dates[1])->endOfDay();

        //     // Filter transactions within the selected date range
        //     $transactions->whereBetween('created_at', [$startDate, $endDate]);
        // }

        // $transactions = $transactions->get(); // Execute query

        // if ($request->ajax()) {
        //     return response()->json(['transactions' => $transactions]);
        // }

        return view('direct_sell.create', compact('transactions'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // Validate incoming data
        $validatedData = $request->validate([
            'product_type' => 'required|string|max:255',
            'cost_price' => 'required|numeric',
            'sell_price' => 'required|numeric',
            'qty' => 'required|integer',
            'customer_name' => 'nullable|string|max:255',
            'purchase_note' => 'nullable|string',
        ]);

        // Uncomment the line below if you want to return the validated data for testing
        // return response()->json($validatedData); 

        try {
            // Insert the new product into the database using the validated data
            $product = new DirectSales();
            $product->product_type = $validatedData['product_type'];
            $product->direct_cost_price = $validatedData['cost_price']; // Assuming 'cost_price' is the field name
            $product->direct_sell_price = $validatedData['sell_price']; // Assuming 'sell_price' is the field name
            $product->direct_profit = $validatedData['sell_price'] - $validatedData['cost_price']; // Calculate profit if needed
            $product->direct_sold_quantity = $validatedData['qty'];
            $product->direct_customer_name = $validatedData['customer_name'] ?? null; // Optional field, handle null
            $product->purchase_note = $validatedData['purchase_note'] ?? null; // Optional field, handle null

            // Set the direct_date_time to current time if it's not part of the request (you can customize this logic)
            $product->direct_date_time = now(); // Use the current timestamp

            // Save the product
            $product->save();

            // Return success response
            return redirect()->back()->with('success', 'Direct Sale added successfully!');
        } catch (\Exception $e) {
            // Handle any errors during insertion
            return response()->json(['error' => 'Error inserting Direct: ' . $e->getMessage()], 500);
        }
    }


    public function directSaleInvoice($id)
    {
        // Fetch the sale details using Eloquent
        $sale = DirectSales::findOrFail($id);

        // Return the invoice view with the sale data
        return view('direct_sell.invoice', compact('sale'));
    }


    /**
     * Display the specified resource.
     */
    public function show(DirectSales $directSales)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $sale = DirectSales::findOrFail($id);
        $customers = Customer::get();
        return view('direct_sell.edit', compact('sale', 'customers'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'product_type' => 'required|string',
            'sell_price' => 'required|numeric',
            'cost_price' => 'required|numeric',
            'profit' => 'required|numeric',
            'purchase_note' => 'required|string',
            'customer_name' => 'required|string',
            'sold_quantity' => 'required|numeric',
            'date_time' => 'required|date',
        ]);

        $sale = DirectSales::find($id);
        // return $request;

        if (!$sale) {
            return redirect()->route('direct-sales.index')->with('error', 'Direct Sale record not found.');
        }

        $sale->update([
            'product_type' => $request->product_type,
            'direct_sell_price' => $request->sell_price,
            'direct_cost_price' => $request->cost_price,
            'direct_profit' => $request->profit,
            'purchase_note' => $request->purchase_note,
            'direct_customer_name' => $request->customer_name,
            'direct_sold_quantity' => $request->sold_quantity,
            'direct_date_time' => $request->date_time,
        ]);

        return redirect()->route('direct-sales.index')->with('success', 'Direct Sale record updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($directSales)
    {
        // Find the transaction
        $directSales = DirectSales::findOrFail($directSales);

        return $directSales;
        // Try to delete the transaction
        if ($directSales->delete()) {
            return redirect()->route('direct-sales.index')->with('success', 'Successfully deleted!');
        } else {
            // In case the deletion fails
            return redirect()->route('direct-sales.index')->with('error', 'Failed to delete transaction!');
        }
    }
}
