<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\DataTables\ContractDataTable;
use App\Models\Contract;
use App\Models\ContractSetting;
use App\Models\SubscriptionType;
use App\Models\SubscriptionDuration;
use App\Http\Requests\Admin\Contract\StoreContractRequest;
use App\Http\Requests\Admin\Contract\UpdateContractRequest;
use App\Repositories\ContractRepository;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;

class ContractController extends Controller
{
    protected ContractRepository $repository;

    public function __construct(ContractRepository $repository)
    {
        $this->repository = $repository;
    }

    public function index(ContractDataTable $dataTable)
    {
        $subscriptionTypes = SubscriptionType::active()->orderBy('name->en')->get();

        return view('admin.contracts.index', [
            'dataTable' => $dataTable->html(),
            'subscriptionTypes' => $subscriptionTypes,
        ]);
    }

    public function datatable(ContractDataTable $dataTable)
    {
        return $dataTable->ajax();
    }

    public function create()
    {
        $subscriptionTypes    = SubscriptionType::active()->orderBy('name->en')->get();
        $subscriptionDurations = SubscriptionDuration::active()->orderBy('name->en')->get();

        return view('admin.contracts.create', compact('subscriptionTypes', 'subscriptionDurations'));
    }

    public function store(StoreContractRequest $request)
    {
        $this->repository->create($request->validated());
        return response()->json([
            'message' => __('dashboard.contract_created'),
            'redirect_url' => route('admin.contracts.index')
        ]);
    }

    public function show(Contract $contract)
    {
        $contract->load(['subscriptionType', 'subscriptionDuration', 'dependents']);
        $settings = ContractSetting::active()->pluck('content', 'key');

        return view('admin.contracts.show', compact('contract', 'settings'));
    }

    public function edit(Contract $contract)
    {
        $contract->load('dependents');
        $subscriptionTypes    = SubscriptionType::active()->orderBy('name->en')->get();
        $subscriptionDurations = SubscriptionDuration::active()->orderBy('name->en')->get();

        return view('admin.contracts.edit', compact('contract', 'subscriptionTypes', 'subscriptionDurations'));
    }

    public function update(UpdateContractRequest $request, Contract $contract)
    {
        $this->repository->update($contract, $request->validated());
        return response()->json([
            'message' => __('dashboard.contract_updated'),
            'redirect_url' => route('admin.contracts.index')
        ]);
    }

    public function destroy(Contract $contract)
    {
        $result = $this->repository->delete($contract);

        return response()->json([
            'message' => $result['success'] ? __('dashboard.contract_deleted') : __('dashboard.cannot_delete_has_relations'),
            'success' => $result['success'],
            'relations' => $result['relations']
        ]);
    }

    public function updateStatus(Contract $contract)
    {
        $result = $this->repository->statusToggle($contract);

        return response()->json([
            'message' => $result['message'],
            'success' => $result['success']
        ]);
    }

    public function bulkDelete(Request $request)
    {
        $request->validate(['ids' => 'required|array']);
        $result = $this->repository->bulkDelete($request->ids);

        return response()->json([
            'message' => __('dashboard.deleted_success'),
            'success' => true,
            'data' => $result
        ]);
    }

    public function bulkStatus(Request $request)
    {
        $request->validate(['ids' => 'required|array', 'status' => 'required|boolean']);
        $result = $this->repository->bulkStatus($request->ids, $request->status);

        return response()->json([
            'message' => __('dashboard.status_updated'),
            'success' => true,
            'data' => $result
        ]);
    }

    /**
     * Export contract to PDF
     */
    public function exportPdf(Contract $contract)
    {
        $contract->load(['subscriptionType', 'subscriptionDuration', 'dependents']);
        $settings              = ContractSetting::active()->pluck('content', 'key');
        $subscriptionTypes     = SubscriptionType::active()->orderBy('name->ar')->get();
        $subscriptionDurations = SubscriptionDuration::active()->orderBy('id')->get();

        $pdf = Pdf::loadView('admin.contracts.pdf', compact('contract', 'settings', 'subscriptionTypes', 'subscriptionDurations'))
            ->setPaper('a4', 'portrait');

        return $pdf->download('contract-' . $contract->serial_number . '.pdf');
    }

    /**
     * Print view (browser-rendered)
     */
    public function print(Contract $contract)
    {
        $contract->load(['subscriptionType', 'subscriptionDuration', 'dependents']);
        $settings              = ContractSetting::active()->pluck('content', 'key');
        $subscriptionTypes     = SubscriptionType::active()->orderBy('name->ar')->get();
        $subscriptionDurations = SubscriptionDuration::active()->orderBy('id')->get();

        return view('admin.contracts.print', compact('contract', 'settings', 'subscriptionTypes', 'subscriptionDurations'));
    }
}
