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

/**
 * License controller – reactivate with new license key (Monthly, Annual, or Lifetime).
 */
class License extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper(array('url', 'form'));
        $this->load->library('form_validation');
    }

    /**
     * Show reactivation form (license key, name, email).
     */
    public function reactivate() {
        $index_page = $this->config->item('index_page');
        $base = rtrim($this->config->base_url(), '/');
        $base_url = $base . ($index_page ? '/' . $index_page : '') . '/';
        $data = array(
            'base_url' => $base_url,
            'theme_link' => $this->_theme_link(),
            'SITE_TITLE' => 'Jasiri Dynamics System',
            'message' => $this->session->flashdata('message'),
            'error' => $this->session->flashdata('error'),
        );
        $this->load->view('license_reactivate', $data);
    }

    /**
     * Process reactivation: verify with server and save license.lock.
     */
    public function do_reactivate() {
        $this->form_validation->set_rules('license_key', 'License Key', 'required|trim');
        $this->form_validation->set_rules('name', 'Name', 'required|trim');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');

        if ($this->form_validation->run() === false) {
            $this->session->set_flashdata('error', validation_errors(' ', ' '));
            redirect('license/reactivate');
            return;
        }

        $license_key = $this->input->post('license_key');
        $name = $this->input->post('name');
        $email = $this->input->post('email');

        $this->load->library('License_checker');
        $result = $this->license_checker->verify_and_reactivate($license_key, $name, $email);

        if (!empty($result['success'])) {
            $this->session->set_flashdata('message', $result['message']);
            redirect(site_url('login'));
            return;
        }

        $this->session->set_flashdata('error', $result['message']);
        redirect('license/reactivate');
    }

    private function _theme_link() {
        $base = rtrim($this->config->base_url(), '/');
        if (strpos($base, 'index.php') !== false) {
            $base = preg_replace('#/index\.php/??$#', '/', $base);
        }
        return $base . '/theme/';
    }
}
