<?php

namespace App\Controllers;

use App\Models\SuperAdminModel;

class SuperAdmin extends BaseController
{

    protected $api_key = 'jjjhhhghgkkdkdjsjshahytyhwhwyw';
    protected $authorized,$response;
    protected $adminModel,$model;

    public function __construct()
    {
        $this->adminModel = new SuperAdminModel();
        $this->model = new SuperAdminModel();

        $this->response   = service('response');
        $request          = service('request'); // ✅ get request manually

        $header = $request->getHeaderLine('X-Api');
        $token  = str_replace('Bearer ', '', $header);
        $this->authorized = ($token === $this->api_key);

        if (!$this->authorized) {
            $this->response
                ->setJSON([
                    'status'  => 'error',
                    'message' => 'Unauthorized',
                ])
                ->setStatusCode(401)->send();
            exit;
        }
    }


    public function login()
    {
        $model = $this->adminModel->super_admin();

        $username = $this->request->getpost('username');
        $password = $this->request->getpost('password');

        $user = $model->where('username', $username)->where('password', $password)->first();
        if(empty($user)){
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Username or Password is wrong',
            ]);
        }

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Login Success',
            'user' => $user,
        ]);

    }



    public function shops()
    {
        $model = $this->adminModel->registration();

        $shops = $model->orderby('id', 'desc')->findAll();

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Fetch All shops',
            'shops' => $shops,
        ]);

    }


    public function action($seg, $id)
    {
        if ($seg == 'shop') {
            $model = $this->adminModel->registration();
        } else if ($seg == 'shopOO') {
            
        }

        $data = $model->find($id);

        $st = $data['status'] == 1 ? '0' : '1';
        $rem = $data['status'] == 0 ? 'active' : 'inactive';
      
        $model->update($id, ['status' => $st]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => ucwords($seg . ' ' .$rem. ' successfully'),
        ]);


    }










}