<?php

namespace App\Http\Controllers\Admin\Marketing;

use App\Http\Controllers\Controller;
use App\Models\Contract;
use Illuminate\Http\Request;

class ContractController extends Controller
{
    public function index()
    {
        $contracts = Contract::with('merchant')->get();
    }

    public function create()
    {
        return view('admin.marketing.contracts.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'contract_number' => 'required|string|max:100|unique:contracts,contract_number',
            'merchant_id' => 'nullable|integer',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'file' => 'nullable|file|mimes:pdf,doc,docx|max:5120',
            'notes' => 'nullable|string',
        ]);

        if ($request->hasFile('file')) {
            $path = $request->file('file')->store('contracts', 'public');
            $validated['file_path'] = $path;
        }

        Contract::create($validated);
        return redirect()->route('admin.marketing.documents.contracts.index')
            ->with('success', 'Contract created successfully.');
    }

    public function show(Contract $contract)
    {
        return view('admin.marketing.documents.contracts.show', compact('contract'));
    }

    public function edit(Contract $contract)
    {
        return view('admin.marketing.contracts.edit', compact('contract'));
    }

    public function update(Request $request, Contract $contract)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'contract_number' => 'required|string|max:100|unique:contracts,contract_number,' . $contract->id,
            'merchant_id' => 'nullable|integer',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'status' => 'required|in:draft,active,expired,terminated',
            'file' => 'nullable|file|mimes:pdf,doc,docx|max:5120',
            'notes' => 'nullable|string',
        ]);

        if ($request->hasFile('file')) {
            $path = $request->file('file')->store('contracts', 'public');
            $validated['file_path'] = $path;
        }

        $contract->update($validated);
        return redirect()->route('admin.marketing.documents.contracts.index')
            ->with('success', 'Contract updated successfully.');
    }

    public function destroy(Contract $contract)
    {
        $contract->delete();
        return redirect()->route('admin.marketing.documents.contracts.index')
            ->with('success', 'Contract deleted successfully.');
    }
}