<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\AppraisalReview;
use App\Models\FinalRatingAction;
use App\Models\AppraisalFinalScore;

class AppraisalFinalScoreController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

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

    /**
     * Store a newly created resource in storage.
     */
    // public function store(Request $request)
    // {
    //     // Common validation
    //     $request->validate([
    //         'appraisal_review_id' => 'required|exists:appraisal_reviews,id',
    //         'action_type' => 'required|string',
    //         'merit_id' => 'required|nullable|exists:final_rating_actions,id',
    //         'notes' => 'nullable|string', // Ensure the notes field is validated
    //     ]);

    //     $appraisalReview = AppraisalReview::find($request->appraisal_review_id);


    //     // Find the specific final rating action based on the score and action type
    //     $finalRatingAction = FinalRatingAction::where('id', $request->merit_id)->first();

    //     if (!$finalRatingAction) {
    //         return redirect()->back()->with('error', 'Could not find a matching final rating policy.');
    //     }

    //     AppraisalFinalScore::create([
    //         'appraisal_review_id' => $appraisalReview->id,
    //         'final_score' => $appraisalReview->final_score,
    //         'action_type' => $request->action_type,
    //         'final_rating_action_id' => $finalRatingAction->id,
    //         'action_details' => $request->notes
    //     ]);

    //     return redirect()->back()->with('success', 'Final score record created successfully.');
    // }


    public function store(Request $request)
    {
        // 1️⃣ Validate input
        $request->validate([
            'appraisal_review_id' => 'required|exists:appraisal_reviews,id',
            'action_type' => 'required|string|in:merit_increase,bonus_incentive,equity_allocation,promotion,retention_grant,no_increase',
            'merit_id' => 'nullable|exists:final_rating_actions,id',
            'notes' => 'nullable|string',
        ]);

        // 2️⃣ Fetch appraisal review
        $appraisalReview = AppraisalReview::findOrFail($request->appraisal_review_id);
        $employee = $appraisalReview->employee;

        // 3️⃣ Fetch merit rule (FinalRatingAction)
        $finalRatingAction = FinalRatingAction::find($request->merit_id);

        if (!$finalRatingAction) {
            return back()->with('error', 'Could not find a matching merit action.');
        }

        // 4️⃣ Get current employee compensation
        $currentSalary = $employee->user->jobInfo->pay_rate ?? 0;
        // $currentBonus = $employee->current_bonus ?? 0;

        // Initialize outcome variables
        $newSalary = $currentSalary;
        // $newBonus = $currentBonus;
        $newEquity = null;
        $promotionLevel = null;
        $retentionGrant = null;


        $currentSalary = (float) $currentSalary;
        $meritPercent = (float) $finalRatingAction->merit_percent;

        $newSalary = $currentSalary + ($currentSalary * ($meritPercent / 100));

        // 5️⃣ Apply logic based on the selected action
        switch ($request->action_type) {
            case 'merit_increase':
                // Use merit_percent to calculate new salary
                break;
            case 'bonus_incentive':
                $bonusSetup = BonusSetup::where('organisation_id', $employee->organisation_id)
                    ->where('bonus_type', $finalRatingAction->bonus_type ?? 'performance')
                    ->first();

                if ($bonusSetup) {
                    $targetBonus = $employee->user->jobInfo->annual_salary * ($bonusSetup->target_percent / 100);
                    $newBonus = $targetBonus * ($finalRatingAction->bonus_multiplier / 100);
                } else {
                    $newBonus = 0;
                }
                break;


            case 'promotion':
                // Treat promotion as merit increase + maybe custom text

                $promotionLevel = 'Promoted';
                break;

            case 'retention_grant':
                break;

            case 'equity_allocation':
                $equityPlan = EquityPlan::active()->first(); // or pass from form
                if ($equityPlan) {
                    $grantValue = $employee->user->jobInfo->annual_salary * 0.15; // example: 15% of base
                    $shareCount = null;

                    if ($equityPlan->equity_type === 'stock' && $equityPlan->share_price) {
                        $shareCount = round($grantValue / $equityPlan->share_price, 2);
                    }

                    $award = EquityAward::create([
                        'equity_plan_id' => $equityPlan->id,
                        'employee_id' => $employee->id,
                        'grant_value' => $grantValue,
                        'shares_granted' => $shareCount,
                        'vesting_start_date' => now(),
                        'vesting_end_date' => now()->addMonths($equityPlan->vesting_period_months ?? 36),
                    ]);

                    $newEquity = "Granted {$shareCount} shares under {$equityPlan->name}";
                }
                break;

            case 'no_increase':
                // No change
                break;
        }
        $data = [
            'appraisal_review_id' => $appraisalReview->id,
            'final_score' => (double) $appraisalReview->final_score,
            'action_type' => $request->action_type,
            'final_rating_action_id' => $finalRatingAction->id,
            'action_details' => $request->notes ?? $finalRatingAction->extra_notes ?? '',
            'new_salary' => $newSalary ?? 0,
            'bonus_multiplier' => $finalRatingAction->bonus_multiplier ?? 0,
            'new_equity' => $newEquity,
            'promotion_level' => $promotionLevel,
            'retention_grant' => $retentionGrant,
        ];
        // 6️⃣ Save record in AppraisalFinalScore
        $finalScore = AppraisalFinalScore::create($data);

        // 7️⃣ Optionally update the employee record
        // if (in_array($request->action_type, ['merit_increase', 'promotion'])) {
        //     $employee->update(['current_salary' => $newSalary]);
        // }

        // if ($request->action_type === 'bonus_incentive') {
        //     $employee->update(['current_bonus' => $newBonus]);
        // }

        return back()->with('success', 'Final score and compensation outcome saved successfully.');
    }



    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

}
