<?php

namespace App\Controllers;

use App\Models\AdminModel;

class Home extends BaseController
{

    protected $api_key = 'jjjhhhghgkkdkdjsjshahytyhwhwyw';
    protected $authorized;
    protected $adminModel;

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

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

    public function index()
    {
        return view('welcome_message');
    }

    public function registration()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }

        if (!$this->authorized) {
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }

        // Check if phone number already exists
        $phone_no = $this->request->getPost('phone');
        $this->adminModel->registrationTable();
        $existingUser = $this->adminModel->where('phone_no', $phone_no)->first();
        if ($existingUser) {
            return $this->response->setJSON(['status' => false, 'error' => 'Phone number already registered']);
        }

        $shop_name = $this->request->getPost('shop_name');
        $owner_name = $this->request->getPost('owner_name');
        $dob = $this->request->getPost('dob');
        $gst_number = $this->request->getPost('gst_number');
        $alternative_phone_no = $this->request->getPost('alt_phone');
        $address = $this->request->getPost('address');
        $city = $this->request->getPost('city');
        $state = $this->request->getPost('state');
        $pincode = $this->request->getPost('pincode');

        // Convert date format from DD/MM/YYYY to YYYY-MM-DD
        $dob = \DateTime::createFromFormat('d/m/Y', $dob);
        if ($dob) {
            $dob = $dob->format('Y-m-d');
        } else {
            // Try alternative format if the above fails
            $dob = date('Y-m-d', strtotime($dob));
        }

        $data = [
            'shop_name' => $shop_name,
            'owner_name' => $owner_name,
            'dob' => $dob,
            'gst_number' => $gst_number,
            'phone_no' => $phone_no,
            'alternative_phone_no' => $alternative_phone_no,
            'address' => $address,
            'city' => $city,
            'state' => $state,
            'pincode' => $pincode,
            'otp_verify' => 0,
            'created_at' => date('Y-m-d H:i:s')
        ];

        // Remove the early return statement that was preventing the database insert
        // return $this->response->setJSON($data);

        if ($this->adminModel->insert($data)) {
            $otp = $this->sendSMS($phone_no);

            // Update the OTP in the database
            $this->adminModel->update($this->adminModel->getInsertID(), ['otp' => $otp]);


            $newUser = $this->adminModel->where('phone_no', $phone_no)->first();
            $response = [
                'status' => true,
                'data' => $newUser,
                'message' => 'Registration successful'
            ];
            return $this->response->setJSON($response);
        } else {
            $response = [
                'status' => false,
                'error' => 'Registration failed - database error'
            ];
            return $this->response->setJSON($response);
        }
    }

    public function sendSMS($mob_no)
    {
        $otp = random_int(1000, 9999);
        $baseUrl = "http://139.99.131.165/api/v2/SendSMS";

        // Static message content
        $message = "Dear Member registration_otp-$otp Recovered Month of APR-25 Rs.24659. "
            . "Thrift:1500 Installment:21/45, Principal:19000, Interest: 0 "
            . "Insurance:0 Others:0 THURAIYUR TNEBECS www.brightecs.com/ym76/sms/m2504.php?recno=25002 BRIGHT TECH";

        // Build URL with parameters (no need to manually urlencode message, http_build_query handles it)
        $fullUrl = $baseUrl . '?' . http_build_query([
            'SenderId' => 'BRITUK',
            'Is_Unicode' => 'false',
            'Is_Flash' => 'false',
            'Message' => $message,
            'MobileNumbers' => $mob_no,
            'ApiKey' => 'e48fce64-3370-462f-b330-da7831888d94',
            'ClientId' => 'b9808c6d-14c5-49f9-8c37-2b417c44911e'
        ]);

        // Send SMS using file_get_contents
        $response = @file_get_contents($fullUrl);

        if ($response === false) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'SMS API request failed',
            ]);
        }

        return $otp;

        // return $this->response->setJSON([
        //     'status' => 'success',
        //     // 'otp'     => $otp
        // ]);

    }
    public function otpVerify()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }

        if (!$this->authorized) {
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }

        $phone_no = $this->request->getPost('phone');
        $otp = $this->request->getPost('otp');
        // return $this->response->setJSON(['status' => "false", 'message' => 'OTP verified successfully','phone_no'=>$phone_no,'otp'=>$otp]);

        $this->adminModel->registrationTable();
        $user = $this->adminModel->where('phone_no', $phone_no)->first();

        if (!$user) {
            return $this->response->setJSON(['status' => false, 'error' => 'User not found']);
        }

        if ($user['otp'] != $otp) {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid OTP']);
        }

        // Update otp_verify to 1
        $this->adminModel->update($user['id'], ['otp_verify' => 1]);

        return $this->response->setJSON(['status' => true, 'message' => 'OTP verified successfully', 'data' => $user]);
    }

    public function AddCategories()
    {
        // Log the request for debugging
        log_message('debug', 'AddCategories method called');
        log_message('debug', 'Request method: ' . $_SERVER['REQUEST_METHOD']);
        log_message('debug', 'POST data: ' . print_r($_POST, true));
        log_message('debug', 'Headers: ' . print_r(getallheaders(), true));

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            log_message('error', 'Invalid request method: ' . $_SERVER['REQUEST_METHOD']);
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }

        if (!$this->authorized) {
            log_message('error', 'Unauthorized request');
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }

        $categoryName = $this->request->getPost('categoryName');
        log_message('debug', 'Received categoryName: ' . $categoryName);

        // Validate category name
        if (empty($categoryName) || $categoryName === null) {
            log_message('error', 'categoryName is empty or null');
            return $this->response->setJSON(['status' => false, 'error' => 'Category name is required']);
        }

        $this->adminModel->categoriesTable();
        $data = [
            'categoryName' => $categoryName,
        ];

        log_message('debug', 'Data to insert: ' . print_r($data, true));

        if ($this->adminModel->insert($data)) {
            log_message('debug', 'Category inserted successfully: ' . $categoryName);
            return $this->response->setJSON(['status' => true, 'message' => 'Category added successfully']);
        } else {
            log_message('error', 'Failed to insert category: ' . $categoryName);
            return $this->response->setJSON(['status' => false, 'error' => 'Failed to add category']);
        }
    }
    
    public function showCategories()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }

        if (!$this->authorized) {

            $this->response->setJSON([
                'status' => 'error',
                'message' => 'Unauthorized',
                'header' => $this->request->getHeaderLine('X-Api')
            ])->setStatusCode(401)->send();
            exit;
        }



        $this->adminModel->categoriesTable();
        $categories = $this->adminModel->findAll();

        return $this->response->setJSON(['status' => true, 'data' => $categories]);
    }
      public function editCategories()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }

        if (!$this->authorized) {
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }

        $id = $this->request->getPost('categoryId');
        $categoryName = $this->request->getPost('categoryName');
        
        // Validate inputs
        if (empty($id) || empty($categoryName)) {
            return $this->response->setJSON(['status' => false, 'error' => 'ID and Category name are required']);
        }

        $this->adminModel->categoriesTable();
        $category = $this->adminModel->where('id', $id)->first();

        if (!$category) {
            return $this->response->setJSON(['status' => false, 'error' => 'Category not found']);
        }

        // Update category
        $updateData = ['categoryName' => $categoryName];
        if ($this->adminModel->update($id, $updateData)) {
            return $this->response->setJSON(['status' => true, 'message' => 'Category updated successfully']);
        } else {
            return $this->response->setJSON(['status' => false, 'error' => 'Failed to update category']);
        }
    }

    public function deleteCategories()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }

        if (!$this->authorized) {
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }

        $id = $this->request->getPost('categoryId');

        // Validate input
        if (empty($id)) {
            return $this->response->setJSON(['status' => false, 'error' => 'Category ID is required']);
        }

        $this->adminModel->categoriesTable();
        $category = $this->adminModel->where('id', $id)->first();

        if (!$category) {
            return $this->response->setJSON(['status' => false, 'error' => 'Category not found']);
        }

        // Delete category
        if ($this->adminModel->delete($id)) {
            return $this->response->setJSON(['status' => true, 'message' => 'Category deleted successfully']);
        } else {
            return $this->response->setJSON(['status' => false, 'error' => 'Failed to delete category']);
        }
    }

    public function fetchSubCategories()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }

        if (!$this->authorized) {
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }
        $categoryId = $this->request->getPost('categoryId');
        if (empty($categoryId)) {
            return $this->response->setJSON(['status' => false, 'error' => 'Category ID is required']);
        }

        // For demonstration, returning static sub-categories
        $this->adminModel->subCategoriesTable();
        $subCategories = $this->adminModel->where('categoryId', $categoryId)->findAll();

        return $this->response->setJSON(['status' => true, 'data' => $subCategories]);
    }

    public function categoriesCount()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }

        if (!$this->authorized) {
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }

        $this->adminModel->categoriesTable();
        $count = $this->adminModel->countAll();

        return $this->response->setJSON(['status' => true, 'count' => $count]);
    }

    public function subCategoriesCount()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }

        if (!$this->authorized) {
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }

        $this->adminModel->subCategoriesTable();
        $count = $this->adminModel->countAll();

        return $this->response->setJSON(['status' => true, 'count' => $count]);
    }

    public function addSubCategories()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }
        
        if (!$this->authorized) {
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }

        $categoryName = $this->request->getPost('categoryName');
        $categoryId = $this->request->getPost('categoryId');
        $subCategoryName = $this->request->getPost('subcategoryName');
        

        // Validate inputs
        if (empty($categoryId) || empty($subCategoryName)) {
            return $this->response->setJSON(['status' => false, 'error' => 'Category ID and Subcategory name are required']);
        }

        $this->adminModel->subCategoriesTable();
        $data = [
            'categoryName' => $categoryName,
            'categoryId' => $categoryId,
            'subCategoryName' => $subCategoryName,
        ];

        if ($this->adminModel->insert($data)) {
            return $this->response->setJSON(['status' => true, 'message' => 'Subcategory added successfully']);
        } else {
            return $this->response->setJSON(['status' => false, 'error' => 'Failed to add subcategory']);
        }
    }

    public function editSubCategories()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }
        
        if (!$this->authorized) {
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }

        $id = $this->request->getPost('subcategoryId');
       
        $subCategoryName = $this->request->getPost('subcategoryName');
        
        // Validate inputs
        if (empty($id) || empty($subCategoryName)) {
            return $this->response->setJSON(['status' => false, 'error' => 'ID and Subcategory name are required']);
        }
        $this->adminModel->subCategoriesTable();
        $subCategory = $this->adminModel->where('id', $id)->first();

        if (!$subCategory) {
            return $this->response->setJSON(['status' => false, 'error' => 'Subcategory not found']);
        }

        $this->adminModel->update($id, ['subCategoryName' => $subCategoryName]);
        return $this->response->setJSON(['status' => true, 'message' => 'Subcategory updated successfully']);
    }

    public function deleteSubCategories()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return $this->response->setJSON(['status' => false, 'error' => 'Invalid request method']);
        }
        
        if (!$this->authorized) {
            return $this->response->setJSON(['status' => false, 'error' => 'Unauthorized']);
        }

        $id = $this->request->getPost('subcategoryId');

        // Validate input
        if (empty($id)) {
            return $this->response->setJSON(['status' => false, 'error' => 'Subcategory ID is required']);
        }

        $this->adminModel->subCategoriesTable();
        $subCategory = $this->adminModel->where('id', $id)->first();

        if (!$subCategory) {
            return $this->response->setJSON(['status' => false, 'error' => 'Subcategory not found']);
        }

        if ($this->adminModel->delete($id)) {
            return $this->response->setJSON(['status' => true, 'message' => 'Subcategory deleted successfully']);
        } else {
            return $this->response->setJSON(['status' => false, 'error' => 'Failed to delete subcategory']);
        }
    }
        

       
    
}
