<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\ProposalApprovalService;

use App\Http\Requests\StoreProposalRequest;
use App\Http\Requests\UpdateProposalRequest;
use App\Models\Product;
use App\Models\Proposal;
use App\Models\ProposalHistory;
use App\Models\Client;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ProposalController extends Controller
{
    // protected $approvalService;

    // public function __construct(ProposalApprovalService $approvalService)
    // {
    //     $this->approvalService = $approvalService;
    // }
    protected $approvalService;

    public function __construct(
        ProposalApprovalService $approvalService
    ) {
        $this->approvalService =
            $approvalService;
    }

    /**
     * Display a listing of proposals with visibility filtering
     */
    // public function index()
    // {
    //     $user = Auth::user();
    //     $query = Proposal::with('product', 'createdBy', 'currentHandler');

    //     // Apply visibility filters based on user role
    //     switch ($user->role->slug) {
    //         case 'vp':
    //             // VP can see all proposals
    //             break;
    //         case 'sd':
    //             // SD can see proposals from their state
    //             $query->where('state_id', $user->state_id);
    //             break;
    //         case 'rm':
    //             // RM can see proposals from their district
    //             $query->where('district_id', $user->district_id);
    //             break;
    //         case 'bdm':
    //             // BDM can see proposals from their city
    //             $query->where('city_id', $user->city_id);
    //             break;
    //         case 'bde':
    //             // BDE can see only their own proposals
    //             $query->where('created_by', $user->id);
    //             break;
    //     }

    //     $proposals = $query->paginate(15);

    //     return view('proposals.index', compact('proposals'));
    // }
    // public function index()
    // {
    //     $user = Auth::user();

    //     $query = Proposal::with([
    //         'product',
    //         'client',
    //         'createdBy',
    //         'currentHandler',
    //     ]);

    //     if ($user->role->slug != 'vp') {

    //         $subordinateIds =
    //             $user->getDescendantIds();

    //         $allowedIds =
    //             array_merge(
    //                 [$user->id],
    //                 $subordinateIds
    //             );

    //         $query->whereIn(
    //             'created_by',
    //             $allowedIds
    //         );
    //     }

    //     if ($user->role->slug == 'sd') {

    //         $query->where(
    //             'state_id',
    //             $user->state_id
    //         );
    //     }

    //     if ($user->role->slug == 'rm') {

    //         $query->where(
    //             'district_id',
    //             $user->district_id
    //         );
    //     }

    //     if ($user->role->slug == 'bdm') {

    //         $query->where(
    //             'city_id',
    //             $user->city_id
    //         );
    //     }

    //     if ($user->role->slug == 'bde') {

    //         $query->where(
    //             'created_by',
    //             $user->id
    //         );
    //     }

    //     $proposals = $query
    //         ->latest()
    //         ->paginate(15);

    //     return view(
    //         'proposals.index',
    //         compact('proposals')
    //     );
    // }
    public function index()
    {
        $user = auth()->user();

        $query = Proposal::with([
            'product',
            'createdBy.role',
            'currentHandler.role',
        ]);

        /*
    |--------------------------------------------------------------------------
    | Visibility Rules
    |--------------------------------------------------------------------------
    */

        if ($user->role->slug == 'vp') {

            // All proposals
        } elseif ($user->role->slug == 'sd') {

            $query->where(
                'state_id',
                $user->state_id
            );
        } elseif ($user->role->slug == 'rm') {

            $query->where(
                'district_id',
                $user->district_id
            );
        } elseif ($user->role->slug == 'bdm') {

            $query->where(
                'city_id',
                $user->city_id
            );
        } elseif ($user->role->slug == 'bde') {

            $query->where(
                'created_by',
                $user->id
            );
        }

        $proposals =
            $query->latest()->paginate(15);

        return view(
            'proposals.index',
            compact('proposals')
        );
    }

    /**
     * Show the form for creating a new proposal
     */
    public function create()
    {
        $products = Product::where('status', true)->get();

        $user = Auth::user();

        // Load geographic data based on user's location
        $country = $user->country;
        $state = $user->state;
        $district = $user->district;
        $city = $user->city;

        return view('proposals.create', compact('products', 'country', 'state', 'district', 'city'));
    }

    /**
     * Store a newly created proposal
     */
    // public function store(StoreProposalRequest $request)
    // {
    //     $user = Auth::user();
    //     $product = Product::findOrFail($request->product_id);

    //     $proposal = Proposal::create([
    //         'proposal_number' => $this->generateProposalNumber(),
    //         'product_id' => $request->product_id,
    //         'created_by' => $user->id,
    //         'country_id' => $user->country_id,
    //         'state_id' => $user->state_id,
    //         'district_id' => $user->district_id,
    //         'city_id' => $user->city_id,
    //         'original_price' => $product->price ?? 0,
    //         'requested_price' => $request->requested_price,
    //         'discount_percentage' => $request->discount_percentage ?? 0,
    //         'gst_percentage' => $request->gst_percentage ?? 18,
    //         'payment_terms' => $request->payment_terms,
    //         'delivery_terms' => $request->delivery_terms,
    //         'installation_notes' => $request->installation_notes,
    //         'terms_and_conditions' => $request->terms_and_conditions,
    //         'valid_until' => $request->valid_until,
    //         'status' => 'draft',
    //     ]);

    //     // Calculate amounts
    //     $this->approvalService->calculateAmounts($proposal);

    //     return redirect()->route('proposals.show', $proposal)
    //         ->with('success', 'Proposal created successfully.');
    // }

    public function store(Request $request)
    {
        $request->validate([

            // Client
            'company_name' => 'required|string|max:255',
            'contact_person' => 'required|string|max:255',
            'phone' => 'required|string|max:20',

            // Proposal
            'product_id' => 'required|exists:lift_products,id',
            'requested_price' => 'required|numeric|min:1',

        ]);

        DB::beginTransaction();

        try {

            /*
        |--------------------------------------------------------------------------
        | Product
        |--------------------------------------------------------------------------
        */

            $product = Product::findOrFail($request->product_id);

            $originalPrice = $product->base_price;

            $requestedPrice = $request->requested_price;

            /*
        |--------------------------------------------------------------------------
        | Discount Calculation
        |--------------------------------------------------------------------------
        */

            $discountAmount =
                $originalPrice - $requestedPrice;

            $discountPercentage =
                ($discountAmount / $originalPrice) * 100;

            /*
        |--------------------------------------------------------------------------
        | GST
        |--------------------------------------------------------------------------
        */

            $gstPercentage =
                $request->gst_percentage ?? 18;

            $gstAmount =
                ($requestedPrice * $gstPercentage) / 100;

            $finalAmount =
                $requestedPrice + $gstAmount;

            /*
        |--------------------------------------------------------------------------
        | Create Client
        |--------------------------------------------------------------------------
        */

            $client = Client::create([

                'client_code' =>
                'CLI-' . time(),

                'company_name' =>
                $request->company_name,

                'contact_person' =>
                $request->contact_person,

                'phone' =>
                $request->phone,

                'alternate_phone' =>
                $request->alternate_phone,

                'email' =>
                $request->email,

                'country_id' =>
                Auth::user()->country_id,

                'state_id' =>
                Auth::user()->state_id,

                'district_id' =>
                Auth::user()->district_id,

                'city_id' =>
                Auth::user()->city_id,

                'address' =>
                $request->address,

                'pincode' =>
                $request->pincode,

                'gst_number' =>
                $request->gst_number,

                'assigned_bde_id' =>
                Auth::id(),

                'created_by' =>
                Auth::id(),

                'status' =>
                'lead',
            ]);

            /*
        |--------------------------------------------------------------------------
        | Create Proposal
        |--------------------------------------------------------------------------
        */

            $proposal = Proposal::create([

                'proposal_number' =>
                'PROP-' . time(),

                'reference_number' =>
                'REF-' . rand(1000, 9999),

                'client_id' =>
                $client->id,

                'product_id' =>
                $product->id,

                'created_by' =>
                Auth::id(),

                'assigned_bde_id' =>
                Auth::id(),

                'current_handler_id' =>
                null,

                'country_id' =>
                Auth::user()->country_id,

                'state_id' =>
                Auth::user()->state_id,

                'district_id' =>
                Auth::user()->district_id,

                'city_id' =>
                Auth::user()->city_id,

                'original_price' =>
                $originalPrice,

                'requested_price' =>
                $requestedPrice,

                'approved_price' =>
                null,

                'discount_percentage' =>
                $discountPercentage,

                'discount_amount' =>
                $discountAmount,

                'gst_percentage' =>
                $gstPercentage,

                'gst_amount' =>
                $gstAmount,

                'final_amount' =>
                $finalAmount,

                'approval_level' =>
                null,

                'status' =>
                'pending_approval',

                'payment_terms' =>
                $request->payment_terms,

                'delivery_terms' =>
                $request->delivery_terms,

                'installation_notes' =>
                $request->installation_notes,

                'terms_and_conditions' =>
                $request->terms_and_conditions,

                'submitted_at' =>
                now(),
            ]);

            /*
        |--------------------------------------------------------------------------
        | Proposal History
        |--------------------------------------------------------------------------
        */

            ProposalHistory::create([

                'proposal_id' =>
                $proposal->id,

                'action_by' =>
                Auth::id(),

                'role_id' =>
                Auth::user()->role_id,

                'action_type' =>
                'created',

                'old_price' =>
                null,

                'new_price' =>
                $requestedPrice,

                'old_discount' =>
                null,

                'new_discount' =>
                $discountPercentage,

                'remarks' =>
                'Proposal created by BDE',
            ]);

            /*
        |--------------------------------------------------------------------------
        | Start Approval Workflow
        |--------------------------------------------------------------------------
        */

            $this->approvalService
                ->initiateApprovalWorkflow($proposal);

            DB::commit();

            return redirect()
                ->route('proposals.index')
                ->with('success', 'Proposal created successfully.');
        } catch (\Exception $e) {
            DB::rollBack();

            return back()
                ->withInput()
                ->with('error', $e->getMessage());
        }
    }

    /**
     * Display the specified proposal
     */
    // public function show(Proposal $proposal)
    // {
    //     // Check visibility
    //     if (! $this->approvalService->canViewProposal(auth()->user(), $proposal)) {
    //         abort(403, 'Unauthorized to view this proposal.');
    //     }

    //     $proposal->load('product', 'createdBy', 'currentHandler', 'approvals', 'histories');
    //     $canApprove = $this->approvalService->canApproveProposal(auth()->user(), $proposal);

    //     return view('proposals.show', compact('proposal', 'canApprove'));
    // }
    public function show(
        Proposal $proposal
    ) {
        $proposal->load([

            'client',

            'product',

            'createdBy.role',

            'currentHandler.role',

            'approvals.approver',

            'histories.actionBy',
        ]);

        /*
    |--------------------------------------------------------------------------
    | Check visibility
    |--------------------------------------------------------------------------
    */

        if (
            ! $this->approvalService
                ->canViewProposal(
                    auth()->user(),
                    $proposal
                )
        ) {
            abort(403);
        }

        /*
    |--------------------------------------------------------------------------
    | Can approve?
    |--------------------------------------------------------------------------
    */

        $this->approvalService
            ->ensureApprovalWorkflow($proposal);

        $canApprove =
            $this->approvalService
            ->canApproveProposal(
                auth()->user(),
                $proposal
            );

        return view(
            'proposals.show',
            compact(
                'proposal',
                'canApprove'
            )
        );
    }

    /**
     * Show the form for editing a proposal
     */
    public function edit(Proposal $proposal)
    {
        // Only creator or VP can edit
        if (auth()->id() !== $proposal->created_by && auth()->user()->role->slug !== 'vp') {
            abort(403, 'Unauthorized to edit this proposal.');
        }

        $products = Product::where('status', true)->get();

        return view('proposals.edit', compact('proposal', 'products'));
    }

    /**
     * Update the specified proposal
     */
    public function update(UpdateProposalRequest $request, Proposal $proposal)
    {
        // Only draft proposals can be edited
        if ($proposal->status !== 'draft') {
            return redirect()->back()->with('error', 'Only draft proposals can be edited.');
        }

        $proposal->update($request->validated());
        $this->approvalService->calculateAmounts($proposal);

        return redirect()->route('proposals.show', $proposal)
            ->with('success', 'Proposal updated successfully.');
    }

    /**
     * Remove the specified proposal
     */
    public function destroy(Proposal $proposal)
    {
        // Only creator or VP can delete
        if (auth()->id() !== $proposal->created_by && auth()->user()->role->slug !== 'vp') {
            abort(403, 'Unauthorized to delete this proposal.');
        }

        // Only draft proposals can be deleted
        if ($proposal->status !== 'draft') {
            return redirect()->back()->with('error', 'Only draft proposals can be deleted.');
        }

        $proposal->delete();

        return redirect()->route('proposals.index')
            ->with('success', 'Proposal deleted successfully.');
    }

    /**
     * Submit proposal for approval
     */
    public function submit(Proposal $proposal)
    {
        if ($proposal->status !== 'draft') {
            return redirect()->back()->with('error', 'Only draft proposals can be submitted.');
        }

        $this->approvalService->submitProposal($proposal, [
            'requested_price' => $proposal->requested_price,
            'discount_percentage' => $proposal->discount_percentage,
            'gst_percentage' => $proposal->gst_percentage,
        ]);

        return redirect()->route('proposals.show', $proposal)
            ->with('success', 'Proposal submitted for approval.');
    }

    /**
     * Approve proposal (for approvers only)
     */
    // public function approve(Request $request, Proposal $proposal)
    // {
    //     if (! $this->approvalService->canApproveProposal(auth()->user(), $proposal)) {
    //         abort(403, 'You do not have permission to approve this proposal.');
    //     }

    //     $request->validate([
    //         'comments' => ['nullable', 'string'],
    //         'discount_percentage' => ['nullable', 'numeric', 'min:0', 'max:100'],
    //     ]);

    //     $this->approvalService->approveProposal($proposal, auth()->user(), $request->all());

    //     return redirect()->route('proposals.show', $proposal)
    //         ->with('success', 'Proposal approved successfully.');
    // }

    public function approve(
        Request $request,
        Proposal $proposal
    ) {
        $user = auth()->user();

        $this->approvalService
            ->ensureApprovalWorkflow($proposal);

        /*
    |--------------------------------------------------------------------------
    | Authorization
    |--------------------------------------------------------------------------
    */

        if (
            ! $this->approvalService
                ->canApproveProposal(
                    $user,
                    $proposal
                )
        ) {
            abort(403);
        }

        /*
    |--------------------------------------------------------------------------
    | Approve
    |--------------------------------------------------------------------------
    */

        $this->approvalService
            ->approveProposal(
                $proposal,
                $user,
                [
                    'comments' =>
                    $request->comments,
                ]
            );

        return back()->with(
            'success',
            'Proposal approved successfully.'
        );
    }

    /**
     * Reject proposal (for approvers only)
     */
    // public function reject(Request $request, Proposal $proposal)
    // {
    //     if ($proposal->current_handler_id !== auth()->id()) {
    //         abort(403, 'You do not have permission to reject this proposal.');
    //     }

    //     $request->validate([
    //         'reason' => ['required', 'string'],
    //     ]);

    //     $this->approvalService->rejectProposal($proposal, auth()->user(), $request->reason);

    //     return redirect()->route('proposals.show', $proposal)
    //         ->with('success', 'Proposal rejected.');
    // }
    public function reject(
        Request $request,
        Proposal $proposal
    ) {
        $request->validate([

            'reason' =>
            'required|string|max:1000',
        ]);

        $user = auth()->user();

        $this->approvalService
            ->ensureApprovalWorkflow($proposal);

        /*
    |--------------------------------------------------------------------------
    | Authorization
    |--------------------------------------------------------------------------
    */

        if (
            ! $this->approvalService
                ->canApproveProposal(
                    $user,
                    $proposal
                )
        ) {
            abort(403);
        }

        /*
    |--------------------------------------------------------------------------
    | Reject
    |--------------------------------------------------------------------------
    */

        $this->approvalService
            ->rejectProposal(
                $proposal,
                $user,
                $request->reason
            );

        return back()->with(
            'success',
            'Proposal rejected successfully.'
        );
    }

    /**
     * Generate unique proposal number
     */
    private function generateProposalNumber(): string
    {
        $date = now()->format('Ymd');
        $count = Proposal::whereDate('created_at', now()->toDateString())->count() + 1;

        return 'PROP-' . $date . '-' . str_pad($count, 4, '0', STR_PAD_LEFT);
    }
}
