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

class Versions extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->database(); // Load database
        $this->load->library('session'); // Load session for flash messages
    }

    // Load the version update view
    public function index() {
        // Fetch the latest version from the database
        $query = $this->db->order_by('id', 'DESC')->get('app_versions', 1);
        $current_version = $query->row();

        // Set data for the view
        $data['current_version'] = $current_version ? $current_version->version_number : 1.0;
        $data['file_path'] = $current_version ? $current_version->file_path : '';

        // Retrieve any flash messages (error/success)
        $data['message'] = $this->session->flashdata('message');
        $data['error'] = $this->session->flashdata('error');

        // Load views
        $this->load->view('admin/includes/header', $data);
        $this->load->view('admin/version/update', $data);
        $this->load->view('admin/includes/footer');
    }


    public function update_version() {
        // Fetch the latest version from the database
        $query = $this->db->order_by('id', 'DESC')->get('app_versions', 1);
        $current_version = $query->row();
        $latest_version = $current_version ? $current_version->version_number : 1.0;
    
        // Get version input from the user (ensure it's a number)
        $user_version = $this->input->post('current_version', TRUE);
        if (!is_numeric($user_version) || $user_version <= $latest_version) {
            $user_version = $latest_version + 1.0; // Auto-increment if invalid or not updated
        }
    
        // Ensure the uploads folder exists and is writable
        $upload_path = './uploads/';
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0777, true); // Create the directory if it doesn't exist
        }
    
        // Handle the file upload
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'apk|zip';
        $config['max_size'] = 50000; // 50MB limit
        $config['detect_mime'] = TRUE; // Important for Hostinger
        $config['remove_spaces'] = TRUE; // Fix issues with spaces in filenames

        $this->load->library('upload', $config);

    
        if (!$this->upload->do_upload('version_file')) {
            $this->session->set_flashdata('error', "Upload failed: " . $this->upload->display_errors());
        } else {
            $upload_data = $this->upload->data();
            $file_path = base_url() . 'uploads/' . $upload_data['file_name']; // Corrected path
    
            // Delete all previous versions
            $this->db->empty_table('app_versions');
    
            // Insert the new version into the database
            $data_insert = [
                'version_number' => $user_version,
                'file_path' => $file_path
            ];
            $this->db->insert('app_versions', $data_insert);
    
            // Set success message
            $this->session->set_flashdata('message', "Version updated to $user_version!");
        }
    
        // Redirect back to index (refreshing the page with the latest version details)
        redirect('/admin/versions');
    }


    public function payment_key() {
        $data['payment_key'] = $this->db->get_where('keys', ['type' => 'payment'])->row_array();
        
        // Load flash messages from session
        $data['message'] = $this->session->flashdata('message');
        $data['error'] = $this->session->flashdata('error');
    
        $this->load->view('admin/includes/header', $data);
        $this->load->view('admin/version/payment_key', $data);
        $this->load->view('admin/includes/footer');
    }
    
    public function update_payment_key() {
        $payment_key = trim($this->input->post('payment_key', true)); // Trim input & enable XSS filtering
    
        if (!empty($payment_key)) {
            $data = ['key' => $payment_key];
            $upd = $this->db->update('keys', $data, ['type' => 'payment']);
    
            if ($upd) {
                $this->session->set_flashdata('message', "Payment key updated successfully!");
            } else {
                $this->session->set_flashdata('error', "Failed to update the key.");
            }
        } else {
            $this->session->set_flashdata('error', "Payment key cannot be empty.");
        }
    
        redirect('/admin/versions/payment_key');
    }
    

    

}
