<?php

namespace App\Http\Controllers;

use App\Models\CivilDefenseTerminationLetter;
use App\Models\Elevator;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CivilDefenseTerminationLetterController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('permission:view_civil_defense');
        $this->middleware('permission:view_termination_letters');
        $this->middleware('permission:manage_termination_letters', ['only' => ['create', 'store', 'edit', 'update', 'destroy']]);
    }
    /**
     * Display a listing of the termination letters.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $company_id = session('company_id');

        $query = CivilDefenseTerminationLetter::with(['elevator', 'customer', 'createdBy'])
            ->where('company_id', $company_id);

        // Apply filters if provided
        if ($request->has('customer_id') && $request->customer_id) {
            $query->where('customer_id', $request->customer_id);
        }

        if ($request->has('elevator_id') && $request->elevator_id) {
            $query->where('elevator_id', $request->elevator_id);
        }

        if ($request->has('date_from') && $request->date_from) {
            $query->whereDate('termination_date', '>=', $request->date_from);
        }

        if ($request->has('date_to') && $request->date_to) {
            $query->whereDate('termination_date', '<=', $request->date_to);
        }

        $letters = $query->orderBy('termination_date', 'desc')->paginate(15);

        // Get data for filters
        $customers = Customer::where('company_id', $company_id)->get();
        $elevators = Elevator::where('company_id', $company_id)
            ->where('status', 'under_maintenance')
            ->get();

        return view('civil_defense.termination_letters.index', compact('letters', 'customers', 'elevators'));
    }

    /**
     * Show the form for creating a new termination letter.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $company_id = session('company_id');

        // Get elevators with "under maintenance" status
        $elevators = Elevator::where('company_id', $company_id)
            ->where('status', 'under_maintenance')
            ->get();

        return view('civil_defense.termination_letters.create', compact('elevators'));
    }

    /**
     * Store a newly created termination letter in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'elevator_id' => 'required|exists:elevators,id',
            'customer_id' => 'required|exists:customers,id',
            'customer_address' => 'required|string|max:255',
            'termination_date' => 'required|date',
        ]);

        $company_id = session('company_id');

        CivilDefenseTerminationLetter::create([
            'company_id' => $company_id,
            'elevator_id' => $request->elevator_id,
            'customer_id' => $request->customer_id,
            'customer_address' => $request->customer_address,
            'termination_date' => $request->termination_date,
            'created_by' => Auth::id(),
        ]);

        return redirect()->route('civil-defense.termination-letters.index')
            ->with('success', 'Termination letter created successfully.');
    }

    /**
     * Display the specified termination letter.
     *
     * @param  \App\Models\CivilDefenseTerminationLetter  $letter
     * @return \Illuminate\Http\Response
     */
    public function show(CivilDefenseTerminationLetter $letter)
    {
        // Check if the letter belongs to the current company
        if ($letter->company_id != session('company_id')) {
            abort(403, 'Unauthorized action.');
        }

        $letter->load(['elevator', 'customer', 'createdBy']);

        return view('civil_defense.termination_letters.show', compact('letter'));
    }

    /**
     * Show the form for editing the specified termination letter.
     *
     * @param  \App\Models\CivilDefenseTerminationLetter  $letter
     * @return \Illuminate\Http\Response
     */
    public function edit(CivilDefenseTerminationLetter $letter)
    {
        // Check if the letter belongs to the current company
        if ($letter->company_id != session('company_id')) {
            abort(403, 'Unauthorized action.');
        }

        $company_id = session('company_id');

        // Get elevators with "under maintenance" status
        $elevators = Elevator::where('company_id', $company_id)
            ->where('status', 'under_maintenance')
            ->get();

        $letter->load(['elevator', 'customer']);

        return view('civil_defense.termination_letters.edit', compact('letter', 'elevators'));
    }

    /**
     * Update the specified termination letter in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\CivilDefenseTerminationLetter  $letter
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, CivilDefenseTerminationLetter $letter)
    {
        // Check if the letter belongs to the current company
        if ($letter->company_id != session('company_id')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate([
            'elevator_id' => 'required|exists:elevators,id',
            'customer_id' => 'required|exists:customers,id',
            'customer_address' => 'required|string|max:255',
            'termination_date' => 'required|date',
        ]);

        $letter->update([
            'elevator_id' => $request->elevator_id,
            'customer_id' => $request->customer_id,
            'customer_address' => $request->customer_address,
            'termination_date' => $request->termination_date,
        ]);

        return redirect()->route('civil-defense.termination-letters.index')
            ->with('success', 'Termination letter updated successfully.');
    }

    /**
     * Remove the specified termination letter from storage.
     *
     * @param  \App\Models\CivilDefenseTerminationLetter  $letter
     * @return \Illuminate\Http\Response
     */
    public function destroy(CivilDefenseTerminationLetter $letter)
    {
        // Check if the letter belongs to the current company
        if ($letter->company_id != session('company_id')) {
            abort(403, 'Unauthorized action.');
        }

        $letter->delete();

        return redirect()->route('civil-defense.termination-letters.index')
            ->with('success', 'Termination letter deleted successfully.');
    }

    /**
     * Get customer information for the selected elevator.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function getCustomerInfo(Request $request)
    {
        try {
            $elevator_id = $request->elevator_id;
            $company_id = session('company_id');

            \Log::info('Getting customer info for elevator', [
                'elevator_id' => $elevator_id,
                'company_id' => $company_id
            ]);

            // Validate elevator_id
            if (!$elevator_id || !is_numeric($elevator_id)) {
                \Log::error('Invalid elevator ID provided', ['elevator_id' => $elevator_id]);
                return response()->json(['error' => 'Invalid elevator ID'], 400);
            }

            $elevator = Elevator::with('customer')
                ->where('company_id', $company_id)
                ->where('id', $elevator_id)
                ->first();

            if (!$elevator) {
                \Log::error('Elevator not found', ['elevator_id' => $elevator_id]);
                return response()->json(['error' => 'Elevator not found'], 404);
            }

            if (!$elevator->customer) {
                \Log::error('Customer not found for elevator', ['elevator_id' => $elevator_id, 'customer_id' => $elevator->customer_id]);
                return response()->json(['error' => 'Customer not found for this elevator'], 404);
            }

            $response = [
                'customer_id' => $elevator->customer_id,
                'customer_name' => $elevator->customer->name,
                'customer_phone' => $elevator->customer->phone ?? '',
                'customer_address' => $elevator->customer->address ?? '',
            ];

            \Log::info('Customer info retrieved successfully', $response);
            return response()->json($response);
        } catch (\Exception $e) {
            \Log::error('Error getting customer info', [
                'elevator_id' => $request->elevator_id ?? 'not provided',
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json(['error' => 'An error occurred: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Print the termination letter.
     *
     * @param  \App\Models\CivilDefenseTerminationLetter  $letter
     * @return \Illuminate\Http\Response
     */
    public function print(CivilDefenseTerminationLetter $letter)
    {
        // Check if the letter belongs to the current company
        if ($letter->company_id != session('company_id')) {
            abort(403, 'Unauthorized action.');
        }

        $letter->load(['elevator', 'customer', 'company', 'createdBy']);

        return view('civil_defense.termination_letters.print', compact('letter'));
    }
}
