<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Imports\PromoImport;
use App\Models\Promocode;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Log;
use Maatwebsite\Excel\Facades\Excel;

class SettingController extends Controller
{
    public function promoCode(Request $request)
    {
        $start = Carbon::now()->month(1)->startOfMonth();
        $end   = Carbon::now()->endOfMonth();

        $result = Promocode::whereBetween('created_at', [$start, $end])->paginate(100);

        return view('admin.setting.promocode', ['data' => $result]);
    }
    /**
     * @param Request $request ->file
     *
     * @return [type][string ]
     */
    public function promoCodeCreate(Request $request)
    {
        // 驗證文件
        $request->validate([
            'file' => 'required|mimes:xlsx,xls,csv|max:2048',
        ]);
        $from = $request->input('from'); // 默認來源為 cafeg

        if ($request->hasFile('file')) {
            $file = $request->file('file');
            Log::info('File uploaded: ', [
                'name' => $file->getClientOriginalName(),
                'size' => $file->getSize(),
                'mime' => $file->getMimeType(),
                'path' => $file->getRealPath(),
            ]);

            // 获取整个文件的内容并打印出来
            $data = Excel::toArray([], $file);
            // Log::info('Excel file content: ', $data); // 打印整个数据数组

            // echo '<pre>';
            // print_r($data);
            // exit;

        }

        // 讀取並導入 Excel 文件
        try {
            Excel::import(new PromoImport($from), $file);
            return back()->with('success', '促銷代碼已成功導入！');
        } catch (\Exception $e) {
            return back()->with('error', '導入失敗: ' . $e->getMessage());
        }
    }

    public function adminIndex(Request $request)
    {
        $data = User::paginate(15);

        return view('admin.setting.adminlist', ['data' => $data]);
    }

    public function loginStatus(Request $request)
    {
        $user            = User::where('id', $request->id)->first();
        $user->can_login = $request->can_login;
        $user->save();

        return response()->json([
            'status'    => 'success',
            'msg'       => '狀態已更新',
            'can_login' => $user->can_login,
        ]);

    }

}
