<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Models\Vouchers_Master;
use App\Models\Admin_User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\File;
use App\Services\NotificationService;

class VoucherMasterController extends Controller
{
    public function index()
    {
        // If it's an AJAX/fetch request → return JSON
        if (request()->expectsJson()) {
            $vouchers = Vouchers_Master::orderBy('created_at', 'desc')->get();
            return response()->json($vouchers);
        }

        // Otherwise → return the Blade view
        return view('vouchers.index');
    }

    public function create()
    {
        return view('vouchers.create');
    }

    public function store(Request $request)
    {
        $data = $request->only([
            'voucher_name', 'title', 'description',
            'type', 'trigger', 'limit_type', 'validity', 'status',
            'banner_bg_color', 'status_color', 'status_text_color',
        ]);

        if ($request->hasFile('img_file')) {
            $data['img_file'] = $this->storeVoucherImage($request->file('img_file'));
        }

        $voucher = Vouchers_Master::create($data);
        return response()->json($voucher, 201);
    }

    public function edit($id)
    {
        $role = trim(Auth::guard('admin')->user()->getUserRole());

        if (request()->expectsJson()) {
            $voucher = Vouchers_Master::findOrFail($id);
            return response()->json($voucher);
        }

        return view('vouchers.edit', [
            'id'   => $id,
            'role' => $role,
        ]);
    }

    public function update(Request $request, $id)
    {
        $voucher = Vouchers_Master::findOrFail($id);

        $data = $request->only([
            'voucher_name', 'title', 'description',
            'type', 'trigger', 'limit_type', 'validity', 'status',
            'banner_bg_color', 'status_color', 'status_text_color',
        ]);

        if ($request->hasFile('img_file')) {
            $data['img_file'] = $this->storeVoucherImage($request->file('img_file'));
        }

        $voucher->update($data);
        return response()->json($voucher);
    }

    private function storeVoucherImage($file): string
    {
        $dir = public_path('images/vouchers');
        File::ensureDirectoryExists($dir);
        $filename = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $file->getClientOriginalName());
        $file->move($dir, $filename);
        return url('images/vouchers/' . $filename);
    }
}

?>