<?php
namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\Controller;

class AuthController extends BaseController
{
    protected $userModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
        helper(['url', 'form', 'session']);
    }

    // Login page
    public function index()
    {
        return view('login');
    }

    // Send OTP
    public function sendOTP()
    {
        $phone = $this->request->getPost('phone');
        if (!$phone) return $this->response->setJSON(['success'=>false,'error'=>'Phone is required']);

        $otp = rand(100000, 999999);
        $expiry = date('Y-m-d H:i:s', strtotime('+5 minutes'));

        $existing = $this->userModel->where('phone', $phone)->first();
        if($existing){
            $this->userModel->update($existing['id'], ['otp'=>$otp, 'otp_expiry'=>$expiry]);
        } else {
            $this->userModel->insert(['phone'=>$phone, 'otp'=>$otp, 'otp_expiry'=>$expiry]);
        }

        return $this->response->setJSON(['success'=>true,'otp'=>$otp,'phone'=>$phone]);
    }

    // Verify OTP
    public function verifyOTP()
    {
        $phone = $this->request->getPost('phone');
        $otp   = $this->request->getPost('otp');

        $user = $this->userModel->where('phone', $phone)->where('otp', $otp)->first();

        if($user && strtotime($user['otp_expiry']) > time()){

            // If apartName is empty, set default placeholder
            $apartName = $user['apartName'] ?? 'Select Apartment';

            session()->set([
                'user_id' => $user['id'],
                'phone' => $user['phone'],
                'apartName' => $apartName,
                'isLoggedIn' => true
            ]);

            // Fetch apartment list
            $apartments = $this->userModel->getApartments();

            return $this->response->setJSON([
                'success'=>true,
                'apartments'=>$apartments,
                'apartName'=>$apartName
            ]);
        }

        return $this->response->setJSON(['success'=>false,'error'=>'Invalid OTP or expired']);
    }

    // Save selected apartment
    public function saveApartment()
    {
        $apartId = $this->request->getPost('apartId');
        $userId  = session()->get('user_id');

        if(!$apartId || !$userId){
            return $this->response->setJSON(['success'=>false,'error'=>'Invalid request']);
        }

        $apart = $this->userModel->getApartmentById($apartId);
        if(!$apart) return $this->response->setJSON(['success'=>false,'error'=>'Apartment not found']);

        // Update user's apartment
        $this->userModel->update($userId, ['apartName'=>$apart['apartName']]);

        // Update session immediately
        session()->set('apartName', $apart['apartName']);

        return $this->response->setJSON(['success'=>true,'apartName'=>$apart['apartName'],'redirect'=>site_url('order')]);
    }

    // Logout
    public function logout()
    {
        session()->destroy();
        return redirect()->to(site_url('authController'));
    }
}
