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

class Bills extends Auth_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Bill_model');
        $this->load->model('Account_model');
    }

    /**
     * Bills page
     */
    public function index() {
        $categories = $this->Bill_model->get_categories();
        $accounts = $this->Account_model->get_by_user($this->user->id);
        
        // Get recent bill payments
        $recent_payments = $this->Bill_model->get_payment_history($this->user->id, [], 5);
        
        // Get saved billers
        $saved_billers = $this->Bill_model->get_saved_billers($this->user->id);
        
        $this->data['title'] = 'Pay Bills';
        $this->data['categories'] = $categories;
        $this->data['accounts'] = $accounts;
        $this->data['recent_payments'] = $recent_payments;
        $this->data['saved_billers'] = $saved_billers;
        
        $this->render('bills/index', $this->data);
    }

    /**
     * Category page
     */
    public function category($slug) {
        $category = $this->Bill_model->get_category($slug);
        
        if (!$category) {
            show_404();
            return;
        }
        
        $providers = $this->Bill_model->get_providers($category->id);
        $accounts = $this->Account_model->get_by_user($this->user->id);
        
        $this->data['title'] = $category->name;
        $this->data['category'] = $category;
        $this->data['providers'] = $providers;
        $this->data['accounts'] = $accounts;
        
        $this->render('bills/category', $this->data);
    }

    /**
     * Get providers for a category (AJAX)
     */
    public function get_providers($category_id) {
        $providers = $this->Bill_model->get_providers($category_id);
        $this->success('Providers retrieved', $providers);
    }

    /**
     * Get products/plans for a provider (AJAX)
     */
    public function get_products($provider_id) {
        $products = $this->Bill_model->get_products($provider_id);
        $this->success('Products retrieved', $products);
    }

    /**
     * Buy airtime
     */
    public function airtime() {
        if ($this->input->method() === 'get') {
            $accounts = $this->Account_model->get_by_user($this->user->id);
            $category = $this->Bill_model->get_category('airtime');
            $providers = $this->Bill_model->get_providers($category->id);
            
            $this->data['title'] = 'Buy Airtime';
            $this->data['accounts'] = $accounts;
            $this->data['providers'] = $providers;
            
            $this->render('bills/airtime', $this->data);
            return;
        }
        
        $this->form_validation->set_rules('account_id', 'Account', 'required');
        $this->form_validation->set_rules('phone', 'Phone Number', 'required|min_length[10]');
        $this->form_validation->set_rules('network', 'Network', 'required');
        $this->form_validation->set_rules('amount', 'Amount', 'required|numeric|greater_than[1]');
        
        if (!$this->form_validation->run()) {
            if ($this->input->is_ajax_request()) {
                $this->error('Validation failed', validation_errors());
                return;
            }
            $this->session->set_flashdata('error', validation_errors());
            redirect('bills/airtime');
            return;
        }
        
        // Verify OTP for non-admin users
        if (!$this->is_admin()) {
            $otp_verified = $this->session->userdata('otp_verified_bill_payment');
            if (!$otp_verified || (time() - $otp_verified) > 300) {
                $message = 'Please verify your identity with OTP';
                if ($this->input->is_ajax_request()) {
                    $this->error($message, ['require_otp' => true]);
                    return;
                }
                $this->session->set_flashdata('error', $message);
                redirect('bills/airtime');
                return;
            }
            $this->session->unset_userdata('otp_verified_bill_payment');
        }
        
        $result = $this->Bill_model->buy_airtime(
            $this->user->id,
            $this->input->post('account_id'),
            $this->input->post('phone', TRUE),
            $this->input->post('network', TRUE),
            floatval($this->input->post('amount'))
        );
        
        if ($result['success']) {
            if ($this->input->is_ajax_request()) {
                $this->success($result['message'], ['reference' => $result['reference']]);
                return;
            }
            $this->session->set_flashdata('success', $result['message']);
            redirect('bills');
        } else {
            if ($this->input->is_ajax_request()) {
                $this->error($result['message']);
                return;
            }
            $this->session->set_flashdata('error', $result['message']);
            redirect('bills/airtime');
        }
    }

    /**
     * Pay electricity bill
     */
    public function electricity() {
        if ($this->input->method() === 'get') {
            $accounts = $this->Account_model->get_by_user($this->user->id);
            $category = $this->Bill_model->get_category('electricity');
            $providers = $this->Bill_model->get_providers($category->id);
            
            $this->data['title'] = 'Pay Electricity';
            $this->data['accounts'] = $accounts;
            $this->data['providers'] = $providers;
            
            $this->render('bills/electricity', $this->data);
            return;
        }
        
        $this->form_validation->set_rules('account_id', 'Account', 'required');
        $this->form_validation->set_rules('meter_number', 'Meter Number', 'required');
        $this->form_validation->set_rules('provider_id', 'Provider', 'required');
        $this->form_validation->set_rules('amount', 'Amount', 'required|numeric|greater_than[0]');
        
        if (!$this->form_validation->run()) {
            if ($this->input->is_ajax_request()) {
                $this->error('Validation failed', validation_errors());
                return;
            }
            $this->session->set_flashdata('error', validation_errors());
            redirect('bills/electricity');
            return;
        }
        
        // Verify OTP for non-admin users
        if (!$this->is_admin()) {
            $otp_verified = $this->session->userdata('otp_verified_bill_payment');
            if (!$otp_verified || (time() - $otp_verified) > 300) {
                $message = 'Please verify your identity with OTP';
                if ($this->input->is_ajax_request()) {
                    $this->error($message, ['require_otp' => true]);
                    return;
                }
                $this->session->set_flashdata('error', $message);
                redirect('bills/electricity');
                return;
            }
            $this->session->unset_userdata('otp_verified_bill_payment');
        }
        
        $category = $this->Bill_model->get_category('electricity');
        
        $result = $this->Bill_model->pay_bill([
            'user_id' => $this->user->id,
            'account_id' => $this->input->post('account_id'),
            'category_id' => $category->id,
            'provider_id' => $this->input->post('provider_id'),
            'customer_id' => $this->input->post('meter_number', TRUE),
            'amount' => floatval($this->input->post('amount'))
        ]);
        
        if ($result['success']) {
            $message = $result['message'];
            if (!empty($result['token'])) {
                $message .= ' Token: ' . $result['token'];
            }
            
            if ($this->input->is_ajax_request()) {
                $this->success($result['message'], [
                    'reference' => $result['reference'],
                    'token' => $result['token'] ?? null
                ]);
                return;
            }
            $this->session->set_flashdata('success', $message);
            redirect('bills');
        } else {
            if ($this->input->is_ajax_request()) {
                $this->error($result['message']);
                return;
            }
            $this->session->set_flashdata('error', $result['message']);
            redirect('bills/electricity');
        }
    }

    /**
     * Buy data bundle
     */
    public function data() {
        if ($this->input->method() === 'get') {
            $accounts = $this->Account_model->get_by_user($this->user->id);
            $category = $this->Bill_model->get_category('data');
            $providers = $category ? $this->Bill_model->get_providers($category->id) : [];
            
            $this->data['title'] = 'Buy Data';
            $this->data['accounts'] = $accounts;
            $this->data['providers'] = $providers;
            
            $this->render('bills/data', $this->data);
            return;
        }
        
        $this->form_validation->set_rules('account_id', 'Account', 'required');
        $this->form_validation->set_rules('phone', 'Phone Number', 'required|min_length[10]');
        $this->form_validation->set_rules('provider_id', 'Network', 'required');
        $this->form_validation->set_rules('product_id', 'Data Plan', 'required');
        $this->form_validation->set_rules('amount', 'Amount', 'required|numeric|greater_than[0]');
        
        if (!$this->form_validation->run()) {
            if ($this->input->is_ajax_request()) {
                $this->error('Validation failed', validation_errors());
                return;
            }
            $this->session->set_flashdata('error', validation_errors());
            redirect('bills/data');
            return;
        }
        
        // Verify OTP for non-admin users
        if (!$this->is_admin()) {
            $otp_verified = $this->session->userdata('otp_verified_bill_payment');
            if (!$otp_verified || (time() - $otp_verified) > 300) {
                $message = 'Please verify your identity with OTP';
                if ($this->input->is_ajax_request()) {
                    $this->error($message, ['require_otp' => true]);
                    return;
                }
                $this->session->set_flashdata('error', $message);
                redirect('bills/data');
                return;
            }
            $this->session->unset_userdata('otp_verified_bill_payment');
        }
        
        $result = $this->Bill_model->buy_data(
            $this->user->id,
            $this->input->post('account_id'),
            $this->input->post('phone', TRUE),
            $this->input->post('provider_id'),
            floatval($this->input->post('amount')),
            $this->input->post('plan_name', TRUE)
        );
        
        if ($result['success']) {
            if ($this->input->is_ajax_request()) {
                $this->success($result['message'], ['reference' => $result['reference']]);
                return;
            }
            $this->session->set_flashdata('success', $result['message']);
            redirect('bills');
        } else {
            if ($this->input->is_ajax_request()) {
                $this->error($result['message']);
                return;
            }
            $this->session->set_flashdata('error', $result['message']);
            redirect('bills/data');
        }
    }

    /**
     * Pay TV subscription
     */
    public function tv() {
        if ($this->input->method() === 'get') {
            $accounts = $this->Account_model->get_by_user($this->user->id);
            $category = $this->Bill_model->get_category('tv');
            $providers = $category ? $this->Bill_model->get_providers($category->id) : [];
            
            $this->data['title'] = 'TV Subscription';
            $this->data['accounts'] = $accounts;
            $this->data['providers'] = $providers;
            
            $this->render('bills/tv', $this->data);
            return;
        }
        
        $this->form_validation->set_rules('account_id', 'Account', 'required');
        $this->form_validation->set_rules('smartcard_number', 'Smart Card Number', 'required|min_length[8]');
        $this->form_validation->set_rules('provider_id', 'Provider', 'required');
        $this->form_validation->set_rules('product_id', 'Subscription Plan', 'required');
        $this->form_validation->set_rules('amount', 'Amount', 'required|numeric|greater_than[0]');
        
        if (!$this->form_validation->run()) {
            if ($this->input->is_ajax_request()) {
                $this->error('Validation failed', validation_errors());
                return;
            }
            $this->session->set_flashdata('error', validation_errors());
            redirect('bills/tv');
            return;
        }
        
        // Verify OTP for non-admin users
        if (!$this->is_admin()) {
            $otp_verified = $this->session->userdata('otp_verified_bill_payment');
            if (!$otp_verified || (time() - $otp_verified) > 300) {
                $message = 'Please verify your identity with OTP';
                if ($this->input->is_ajax_request()) {
                    $this->error($message, ['require_otp' => true]);
                    return;
                }
                $this->session->set_flashdata('error', $message);
                redirect('bills/tv');
                return;
            }
            $this->session->unset_userdata('otp_verified_bill_payment');
        }
        
        $category = $this->Bill_model->get_category('tv');
        
        $result = $this->Bill_model->pay_bill([
            'user_id' => $this->user->id,
            'account_id' => $this->input->post('account_id'),
            'category_id' => $category->id,
            'provider_id' => $this->input->post('provider_id'),
            'product_id' => $this->input->post('product_id'),
            'customer_id' => $this->input->post('smartcard_number', TRUE),
            'amount' => floatval($this->input->post('amount'))
        ]);
        
        if ($result['success']) {
            if ($this->input->is_ajax_request()) {
                $this->success($result['message'], ['reference' => $result['reference']]);
                return;
            }
            $this->session->set_flashdata('success', $result['message']);
            redirect('bills');
        } else {
            if ($this->input->is_ajax_request()) {
                $this->error($result['message']);
                return;
            }
            $this->session->set_flashdata('error', $result['message']);
            redirect('bills/tv');
        }
    }

    /**
     * Bill payment history
     */
    public function history() {
        $page = $this->input->get('page') ?: 1;
        $limit = 20;
        $offset = ($page - 1) * $limit;
        
        $filters = [
            'category_id' => $this->input->get('category'),
            'status' => $this->input->get('status')
        ];
        
        $payments = $this->Bill_model->get_payment_history($this->user->id, $filters, $limit, $offset);
        
        $this->data['title'] = 'Bill Payment History';
        $this->data['payments'] = $payments;
        $this->data['categories'] = $this->Bill_model->get_categories();
        $this->data['page'] = $page;
        
        $this->render('bills/history', $this->data);
    }

    /**
     * Generic bill payment
     */
    public function pay() {
        $this->form_validation->set_rules('account_id', 'Account', 'required');
        $this->form_validation->set_rules('category_id', 'Category', 'required');
        $this->form_validation->set_rules('provider_id', 'Provider', 'required');
        $this->form_validation->set_rules('customer_id', 'Customer ID', 'required|min_length[3]');
        $this->form_validation->set_rules('amount', 'Amount', 'required|numeric|greater_than[99]');
        
        // Only require PIN for non-admin users
        if (!$this->is_admin()) {
            $this->form_validation->set_rules('pin', 'PIN', 'required|exact_length[4]');
        }
        
        if (!$this->form_validation->run()) {
            if ($this->input->is_ajax_request()) {
                $this->error('Validation failed', validation_errors());
                return;
            }
            $this->session->set_flashdata('error', validation_errors());
            redirect('bills');
            return;
        }
        
        // Verify PIN only for non-admin users
        if (!$this->is_admin()) {
            if (!$this->verify_pin($this->input->post('pin'))) {
                $message = 'Invalid transaction PIN';
                if ($this->input->is_ajax_request()) {
                    $this->error($message);
                    return;
                }
                $this->session->set_flashdata('error', $message);
                redirect('bills');
                return;
            }
        }
        
        $result = $this->Bill_model->pay_bill([
            'user_id' => $this->user->id,
            'account_id' => $this->input->post('account_id'),
            'category_id' => $this->input->post('category_id'),
            'provider_id' => $this->input->post('provider_id'),
            'customer_id' => $this->input->post('customer_id', TRUE),
            'amount' => floatval($this->input->post('amount'))
        ]);
        
        if ($result['success']) {
            if ($this->input->is_ajax_request()) {
                $this->success($result['message'], ['reference' => $result['reference']]);
                return;
            }
            $this->session->set_flashdata('success', $result['message']);
            redirect('bills');
        } else {
            if ($this->input->is_ajax_request()) {
                $this->error($result['message']);
                return;
            }
            $this->session->set_flashdata('error', $result['message']);
            redirect('bills');
        }
    }

    /**
     * Save biller
     */
    public function save_biller() {
        $this->form_validation->set_rules('category_id', 'Category', 'required');
        $this->form_validation->set_rules('provider_id', 'Provider', 'required');
        $this->form_validation->set_rules('customer_id', 'Customer ID', 'required');
        
        if (!$this->form_validation->run()) {
            $this->error('Validation failed', validation_errors());
            return;
        }
        
        $result = $this->Bill_model->save_biller([
            'user_id' => $this->user->id,
            'category_id' => $this->input->post('category_id'),
            'provider_id' => $this->input->post('provider_id'),
            'nickname' => $this->input->post('nickname', TRUE),
            'customer_id' => $this->input->post('customer_id', TRUE),
            'customer_name' => $this->input->post('customer_name', TRUE)
        ]);
        
        if ($result['success']) {
            $this->success($result['message']);
        } else {
            $this->error($result['message']);
        }
    }
}
