<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {


	   function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->library('session');
        $this->load->helper(['url','common_helper']);

      
    }
    
    private function outputJSON($code,$status,$msg,$data=[]){
    $CI =& get_instance();
    echo json_encode([
        'status' => $status,
        'message'=> $msg,
        'data'   => $data,
        'csrf_name' => $CI->security->get_csrf_token_name(),
        'csrf_hash' => $CI->security->get_csrf_hash()
    ]);
    exit;
}
          
 public function send_otp()
{
   header("Content-Type: application/json; charset=UTF-8");

    if ($this->input->method() !== 'post') {
        $this->outputJSON(405, 'error', 'Invalid request method');
        return;
    }

 
    $phone = $this->security->xss_clean($this->input->post('phone'));
    

        
                if(!preg_match('/^[6-9]\d{9}$/',$phone)){
            $this->outputJSON(200,'error','Invalid phone number'); return;
        }





    /* ---------------------------
       1) BLOCK OTP SPAM (30 sec)
    ----------------------------*/
    $last = $this->db->where('phone',$phone)->order_by('id','DESC')->get('all_otp')->row();
        if($last && strtotime($last->created_at) > time()-30){
            $this->outputJSON(429,'error','Wait 30 seconds'); return;
        }
        

    /* ---------------------------
       2) LOAD SMS TEMPLATE
    ----------------------------*/
    $template = $this->db
        ->where(['status' => 0, 'id' => 1])
        ->get('sms_api_config')
        ->row();

    if (!$template) {
        $this->outputJSON(500, 'error', 'OTP SMS template not configured');
        return;
    }

    /* ---------------------------
       3) GENERATE OTP
    ----------------------------*/
    $otp = rand(1000, 9999);   // 4-digit OTP (secure enough)
    // $otp = 1234; // uncomment only for testing

    $user_name = 'Customer';

    /* ---------------------------
       4) BUILD SMS API URL
    ----------------------------*/
    $api_url = $this->get_api_url();
    $api_url = str_replace(
        ['mobile_number', 'user_name', 'otp_now'],
        [urlencode($phone), urlencode($user_name), $otp],
        $api_url
    );

    /* ---------------------------
       5) SAVE OTP IN DATABASE
    ----------------------------*/
    $otpData = [
        'phone'      => $phone,
        'otp'        => $otp,
        'status'     => 0,
        'created_at'=> date('Y-m-d H:i:s'),
        'expires_at'=> date('Y-m-d H:i:s', time() + 300) // 5 minutes
    ];

    
     if ($this->db->where('phone', $phone)->get('all_otp')->num_rows() > 0) {
        $this->db->update('all_otp', $otpData, ['phone' => $phone]);
    } else {
        $this->db->insert('all_otp', $otpData);
    }


    /* ---------------------------
       6) SEND OTP
    ----------------------------*/
    $api_response = $this->send_request($api_url);

    // Even if SMS API fails, OTP is saved (avoid login blocking)
    
    $this->outputJSON(200, 'success', 'OTP testing sent successfully');
    
    
}

public function expire_otp()
{
    header("Content-Type: application/json");

    if ($this->input->method() !== 'post') {
        $this->outputJSON(405, 'error', 'Invalid request method');
        return;
    }
     
     
                 
   
 
    $phone = $this->security->xss_clean($this->input->post('phone'));
    
                 
             

    if (!preg_match('/^[6-9]\d{9}$/', $phone)) {
        $this->outputJSON(400, 'error', 'Invalid phone number');
        return;
    }

    // Expire all active OTPs
    $this->db->where([
        'phone'  => $phone,
        'status' => 0
    ])->update('all_otp', [
        'status' => 2, // expired
        'updated_at' => date('Y-m-d H:i:s')
    ]);

   $this-> outputJSON(200, 'success', 'OTP expired');
}


// Get SMS API URL
private function get_api_url()
{
    $query = $this->db->get('sms_api_config', 1);
    return $query->row()->api_url;
}

// Send HTTP request
private function send_request($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}


public function verify_otp()
{
    
    header("Content-Type: application/json; charset=UTF-8");

    if ($this->input->method() !== 'post') {
        $this->outputJSON(405, 'error', 'Invalid request method');
        return;
    }
    
    
    
     $phone = $this->security->xss_clean($this->input->post('phone'));
     
     $otp = $this->security->xss_clean($this->input->post('otp'));
    
    
                if(empty($phone)  || empty($otp)){
            $this->outputJSON(200,'error','OTP, Phone number required'); return;
        }
    

    // Validate OTP
    $row = $this->db->where(['phone' => $phone, 'otp' => $otp,'status' => 0])->get('all_otp')->row();

    if (!$row) {
        $this->outputJSON(401, 'error', 'Invalid OTP');
        return;
    }
    
    
     $attempts = $this->db->where('phone',$phone)
                     ->where('attempt_time >',date('Y-m-d H:i:s',strtotime('-10 minutes')))
                     ->count_all_results('otp_attempts');

        if($attempts > 5){
           $this->outputJSON(429,'error','Too many attempts'); return;
        }

        $this->db->insert('otp_attempts',[
            'phone'=>$phone,
            'ip_address'=>$this->input->ip_address(),
            'attempt_time'=>date('Y-m-d H:i:s')
        ]);
        
        
        

    // Expiry check
    if (strtotime($row->expires_at) < time()) {
        $this->db->update('all_otp', ['status' => 2], ['id' => $row->id]);
        $this->outputJSON(401, 'error', 'OTP expired');
        return;
    }

    // Mark OTP as used
    $this->db->update('all_otp', ['status' => 1], ['id' => $row->id]);
    
    $this->session->set_userdata(['otp_verified'=>true,'phone'=>$phone]);

    // Fetch user
    $user = $this->db->get_where('users', ['phone' => $phone])->row();

    if ($user) {

        // 🔐 CREATE LOGIN SESSION
        $this->session->set_userdata([
            'is_logged_in' => true,
            'user_auto_id' => $user->id,
            'user_id'      => $user->user_id,
            'name'         => $user->name,
            'email'        => $user->email,
            'phone'        => $user->phone
        ]);

        $this->outputJSON(200, 'success', 'Login success', [
            'user_exist' => 1,
            'user' => [
                'user_id' => $user->user_id,
                'name'    => $user->name,
                'email'   => $user->email,
                'phone'   => $user->phone
            ]
        ]);
    } 
    else {
        // New user → only phone saved in session
        $this->session->set_userdata([
             'is_logged_in' => true,
            'phone' => $phone
        ]);

        $this->outputJSON(200, 'success', 'New user', [
            'user_exist' => 0,
            'phone' => $phone
        ]);
    }
}


  
    function generateCustomerId() {
    $timestamp = date("His"); // Current date and time
    $randomStr = strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 3)); // Random 6-char string
    return "Cust-" . $timestamp . "-" . $randomStr;
}


public function AddUserdetails()
{
    
    
    if(!$this->session->userdata('otp_verified')){
           $this->outputJSON(403,'error','OTP not verified'); return;
        }



     $email = $this->security->xss_clean($this->input->post('email'));
     
     $name = $this->security->xss_clean($this->input->post('name'));
    
  
        $phone = $this->session->userdata('phone');


    if (empty($name) || empty($email) || empty($phone)) {
        $this->outputJSON(400, 'error', 'All fields required  , Name , Phone , Email');
        return;
    }

    if ($this->db->get_where('users', ['phone' => $phone])->num_rows() > 0) {
        $this->outputJSON(409, 'error', 'Already registered');
        return;
    }

    $customerId = $this->generateCustomerID();

    $user = [
        'user_id' => $customerId,
        'name'    => $name,
        'email'   => $email,
        'phone'   => $phone,
        'domain'  => $_SERVER['HTTP_HOST'],
        'created' => date('Y-m-d H:i:s')
    ];

    $this->db->insert('users', $user);
    $insert_id = $this->db->insert_id();

    // 🔐 AUTO LOGIN SESSION
    $this->session->set_userdata([
        'user_auto_id' => $insert_id,
        'user_id'      => $customerId,
        'name'    => $name,
        'email'   => $email,
        'phone'   => $phone,
    ]);

    $this->outputJSON(200, 'success', 'Registered & Logged in', [
        'user_id' => $customerId,
        'name'    => $name,
        'email'   => $email,
        'phone'   => $phone,
    ]);
}






public function logout()
{
    $this->session->sess_destroy();
    redirect('/');
}

    
   
   
   
   

}