<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class AdminCustomerController extends Controller
{
    // ---------------------------------------------------------
    // LIST CUSTOMERS (with search + status filter)
    // ---------------------------------------------------------
    public function index(Request $request)
    {
        $search = $request->search;
        $status = $request->status;

        $query = User::with(['marks', 'orders'])->orderBy('id', 'desc');

        // SEARCH FILTER
        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('customer_name', 'like', "%$search%")
                    ->orWhere('email', 'like', "%$search%")
                    ->orWhere('mobile_no', 'like', "%$search%")
                    ->orWhere('customer_id', 'like', "%$search%");
            });
        }

        // STATUS FILTER
        if (!empty($status) && in_array($status, ['active', 'inactive'])) {
            $query->where('status', $status);
        }

        $customers = $query->get();

        return view('admin.customers', compact('customers', 'search', 'status'));
    }

    // ---------------------------------------------------------
    // SHOW ADD CUSTOMER FORM
    // ---------------------------------------------------------
    public function create()
    {
        return view('admin.customers_add');
    }

    // ---------------------------------------------------------
    // STORE NEW CUSTOMER
    // ---------------------------------------------------------
    public function store(Request $request)
    {
        $request->validate([
            'customer_name' => 'required|string|max:255',
            'company_name'  => 'nullable|string|max:255',
            'designation'   => 'nullable|string|max:255',
            'email'         => 'required|email|unique:users,email',
            'mobile_no'     => 'required|string|max:20',
            'address'       => 'nullable|string',
            'pincode'       => 'nullable|string|max:10',
            'customer_type' => 'required|in:regular,premium',
            'status'        => 'required|in:active,inactive',
        ]);

        // AUTO GENERATE CUSTOMER ID
        $year = date('Y');
        $prefix = "CID-$year-";

        $lastCustomer = User::whereYear('created_at', $year)
                            ->orderBy('id', 'DESC')
                            ->first();

        $next = $lastCustomer ? intval(substr($lastCustomer->customer_id, -6)) + 1 : 1;
        $customerId = $prefix . str_pad($next, 6, '0', STR_PAD_LEFT);

        // CREATE CUSTOMER
        User::create([
            'customer_id'   => $customerId,
            'customer_name' => $request->customer_name,
            'company_name'  => $request->company_name,
            'designation'   => $request->designation,
            'email'         => $request->email,
            'mobile_no'     => $request->mobile_no,
            'address'       => $request->address,
            'pincode'       => $request->pincode,
            'date'          => date('Y-m-d'),
            'customer_type' => $request->customer_type,
            'status'        => $request->status,
            'password'      => Hash::make('123456'), // DEFAULT PASSWORD
        ]);

        return redirect()
            ->route('admin.customers.index')
            ->with('success', 'Customer added successfully!');
    }

    // ---------------------------------------------------------
    // VIEW CUSTOMER FULL DETAILS
    // ---------------------------------------------------------
    public function view($id)
    {
        $customer = User::with(['marks', 'orders'])->findOrFail($id);

        $totalOrders = $customer->orders->count();
        $totalAmount = $customer->orders->sum('ttl_amount');
        $recentOrders = $customer->orders()->latest()->take(5)->get();

        return view('admin.customers_view', compact(
            'customer',
            'totalOrders',
            'totalAmount',
            'recentOrders'
        ));
    }

    // ---------------------------------------------------------
    // TOGGLE STATUS ACTIVE / INACTIVE
    // ---------------------------------------------------------
    public function toggleStatus($id)
    {
        $customer = User::findOrFail($id);

        $customer->status = $customer->status === 'active'
            ? 'inactive'
            : 'active';

        $customer->save();

        return back()->with('success', 'Customer status updated.');
    }

}
