<?php

namespace App\Http\Controllers;

use App\Models\Contract;
use App\Models\Package;
use App\Services\PdfService;

class ContractController extends Controller
{
    public function createContract($investor_id, $package_id)
    {
        $package = Package::findOrFail($package_id);

        $contract = Contract::create([
            'contract_number' => 'INV-' . time(),
            'investor_id'     => $investor_id,
            'package_id'      => $package->id,
            'capital'         => $package->price,
            'daily_profit'    => $package->daily_profit,
            'total_profit'    => $package->total_profit,
            'start_date'      => now(),
            'end_date'        => now()->addDays($package->duration),
        ]);

        return response()->json([
            'message' => 'Contract created',
            'contract' => $contract
        ]);
    }

    public function download($id, $lang = null)
    {
        // ✅ تغيير اللغة إذا طُلب
        if ($lang && in_array($lang, ['ar', 'en'])) {
            app()->setLocale($lang);
        }

        $contract = Contract::with('investor', 'package')->findOrFail($id);

        // ✅ استخدام mPDF
        $pdfService = new PdfService();
        $mpdf = $pdfService->loadView('contract', compact('contract'), $lang ?? app()->getLocale());

        return $mpdf->Output('contract-' . $contract->contract_number . '.pdf', 'D');
    }
}
