<?php

namespace App\Http\Controllers\Admin;

use App\Constants\Status;
use App\Exports\CouponExport;
use App\Http\Controllers\Controller;
use App\Models\Coupon;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Facades\Excel;
use Barryvdh\DomPDF\Facade\Pdf;

class CouponController extends Controller
{

    public function index()
    {
        $pageTitle = "All Coupons List";
        $emptyMessage = "No coupons found";
        $coupons = Coupon::searchable(['code','user:username,id,system_id'])->dateFilter('published_at')->with('user')->latest()->paginate(getPaginate());
        return view('admin.coupon.index', compact('pageTitle', 'emptyMessage', 'coupons'));
    }

    public function couponExport(Request $request)
    {
        $fileName = 'Coupon-Report- ' . date('Y-m-d') . '.csv';
        return Excel::download(new CouponExport($request), $fileName);
    }
    public function couponPdf(Request $request)
    {
        $coupons = Coupon::searchable(['code','user:username,id,system_id'])->dateFilter('published_at')->with('user')->latest()->get();

        $pdf = PDF::loadView($this->activeTemplate . 'user.pdf_blades.coupon_pdf', compact('coupons'));
        $filename = 'User-debt-free-report-' . date('Y-m-d') . '.pdf';
        return $pdf->download($filename);
    }

    public function editCreate($id = 0)
    {
        $pageTitle = $id ? "Coupon Update" : "Coupon Create";
        $coupon = new Coupon();
        if ($id) {
            $coupon = Coupon::findOrFail($id);
        }
        return view('admin.coupon.edit', compact('coupon'));
    }

    public function updateStore(Request $request, $id = 0)
    {
        $request->validate([
            'code' => 'required',
            'published_at' => 'nullable|date',
            'expires_at' => 'nullable|date',
            'user_id' => 'nullable|integer',
            'status' => 'required|in:' . implode(',', [
                Status::CouponDraft,
                Status::CouponActive,
                Status::CouponExpired,
            ]),
            'used_at' => 'nullable|date',
        ]);

        $coupon = new Coupon();
        if ($id) {
            $coupon = Coupon::findOrFail($id);
        }
        $coupon->code = $request->code;
        $coupon->published_at = $request->published_at ? Carbon::parse($request->published_at) : null;
        $coupon->expires_at = $request->expires_at ? Carbon::parse($request->expires_at) : null;
        $coupon->user_id = $request->user_id;
        $coupon->status = $request->status;
        $coupon->used_at = $request->used_at ? Carbon::parse($request->used_at) : null;
        $coupon->save();

        $notify[] = ['success', 'Coupon '.($id ? 'updated' : 'created').' successfully'];
        return back()->withNotify($notify);
    }

    public function delete(Request $request)
    {
        $coupon = Coupon::findOrFail($request->id);
        $coupon->delete();

        $notify[] = ['success', 'Coupon deleted successfully'];
        return back()->withNotify($notify);
    }

    public function bulkUpload(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:csv,txt',
        ]);

        $file = $request->file('file');
        $fileData = array_map('str_getcsv', file($file));
        foreach ($fileData as $key => $value) {
            if ($key == 0) {
                continue;
            }
            $coupon = new Coupon();
            $coupon->code = $value[0] ?? null;
            $coupon->published_at = $value[1] ?? null;
            $coupon->expires_at = $value[2] ?? null;
            $coupon->used_at = $value[3] ?? null;
            $coupon->user_id = $value[4] ?? null;
            $coupon->status = $value[5] ?? null;
            $coupon->save();
        }

        $notify[] = ['success', 'Bulk coupon upload completed'];
        return back()->withNotify($notify);
    }


    public function sampleBulkUpload()
    {
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="coupon_sample.csv"',
        ];
        $callback = function () {
            $file = fopen('php://output', 'w');
            fputcsv($file, ['code', 'published_at', 'expires_at', 'used_at', 'user_id', 'status']);
            fclose($file);
        };
        return response()->stream($callback, 200, $headers);
    }
}
