<?php

//the global file operation
include("../public/impOpreation.php");

//get the do the action
$do = $_GET['do'];

$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");

$userID = $_SESSION['userid'];
$today = date("Y-m-d H:i:s");

// AJAX actions that skip header/footer
$ajaxActions = array();

if (!in_array($do, $ajaxActions)) {
    $smarty->display("header.html");
}

$smarty->assign("accCommon", 1);
$smarty->assign("accSetup", 1);

//check and use the condition that suits this action
if (empty($do)) {
    // Check if module is already initialized
    $setting = R::getRow("SELECT * FROM acc_settings WHERE setting_key = 'module_initialized' LIMIT 1");
    $isInitialized = (!empty($setting) && $setting['setting_value'] == '1');
    $smarty->assign("already_initialized", $isInitialized ? 1 : 0);

    // Get stats if initialized
    if ($isInitialized) {
        $accountCount = R::getCell("SELECT COUNT(*) FROM acc_account WHERE del = 0");
        $journalCount = R::getCell("SELECT COUNT(*) FROM acc_journal_entry WHERE del = 0");
        $fyData = R::getRow("SELECT * FROM acc_fiscal_year WHERE del = 0 ORDER BY id DESC LIMIT 1");
        $smarty->assign("accountCount", $accountCount);
        $smarty->assign("journalCount", $journalCount);
        $smarty->assign("fyData", $fyData);
    }

    $smarty->display("accSetupview/setup.html");
}

elseif ($do == "resetModule") {
    try {
        $reset_password = isset($_POST['reset_password']) ? $_POST['reset_password'] : '';

        // Verify password
        if ($reset_password !== 'gt4') {
            $smarty->assign("resetError", 1);
            $setting = R::getRow("SELECT * FROM acc_settings WHERE setting_key = 'module_initialized' LIMIT 1");
            $smarty->assign("already_initialized", 1);
            $accountCount = R::getCell("SELECT COUNT(*) FROM acc_account WHERE del = 0");
            $journalCount = R::getCell("SELECT COUNT(*) FROM acc_journal_entry WHERE del = 0");
            $fyData = R::getRow("SELECT * FROM acc_fiscal_year WHERE del = 0 ORDER BY id DESC LIMIT 1");
            $smarty->assign("accountCount", $accountCount);
            $smarty->assign("journalCount", $journalCount);
            $smarty->assign("fyData", $fyData);
            $smarty->display("accSetupview/setup.html");
        } else {
            // Clear all accounting data
            R::exec("DELETE FROM acc_journal_entry_line");
            R::exec("DELETE FROM acc_journal_entry");
            R::exec("DELETE FROM acc_opening_balance");
            R::exec("DELETE FROM acc_budget_line");
            R::exec("DELETE FROM acc_budget");
            R::exec("DELETE FROM acc_account");
            R::exec("DELETE FROM acc_cost_center");
            R::exec("DELETE FROM acc_fiscal_year");
            R::exec("UPDATE acc_settings SET setting_value = '0' WHERE setting_key = 'module_initialized'");
            R::exec("DELETE FROM acc_settings WHERE setting_key = 'default_fiscal_year_id'");

            // Reset auto-increment
            R::exec("ALTER TABLE acc_journal_entry_line AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_journal_entry AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_opening_balance AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_budget_line AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_budget AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_account AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_cost_center AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_fiscal_year AUTO_INCREMENT = 1");

            header("location:accSetupController.php");
            exit;
        }
    } catch (Exception $e) {
        header("location:accSetupController.php?do=error");
        exit;
    }
}

elseif ($do == "initModule") {
    try {
        $template_type = isset($_POST['template_type']) ? $_POST['template_type'] : 'empty';
        $fiscal_year_name = isset($_POST['fiscal_year_name']) ? trim($_POST['fiscal_year_name']) : '';
        $start_date = isset($_POST['start_date']) ? $_POST['start_date'] : '';
        $end_date = isset($_POST['end_date']) ? $_POST['end_date'] : '';

        // Create fiscal year record
        R::exec("INSERT INTO acc_fiscal_year (name, start_date, end_date, status, is_closed, userid, created_at, del) VALUES (?, ?, ?, 1, 0, ?, ?, 0)",
            [$fiscal_year_name, $start_date, $end_date, $userID, $today]);
        $fiscalYearId = R::getCell("SELECT LAST_INSERT_ID()");

        // If a template is chosen, copy accounts from template
        if ($template_type != 'empty') {
            $templates = R::getAll("SELECT * FROM acc_account_template WHERE template_type = ? ORDER BY level, code",
                [$template_type]);

            if (!empty($templates)) {
                $codeToId = array();
                foreach ($templates as $tpl) {
                    $parentId = 0;
                    if (!empty($tpl['parent_code']) && isset($codeToId[$tpl['parent_code']])) {
                        $parentId = $codeToId[$tpl['parent_code']];
                    }

                    R::exec("INSERT INTO acc_account (code, name, parent_id, account_nature, account_type, level, is_leaf, balance, userid, created_at, del) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, 0)",
                        [$tpl['code'], $tpl['name'], $parentId, $tpl['account_nature'], $tpl['account_type'], $tpl['level'], $tpl['is_leaf'], $userID, $today]);
                    $newId = R::getCell("SELECT LAST_INSERT_ID()");
                    $codeToId[$tpl['code']] = $newId;
                }
            }
        }

        // Set module as initialized
        R::exec("UPDATE acc_settings SET setting_value = '1' WHERE setting_key = 'module_initialized'");

        // Set default fiscal year
        $existingFY = R::getRow("SELECT * FROM acc_settings WHERE setting_key = 'default_fiscal_year_id' LIMIT 1");
        if (!empty($existingFY)) {
            R::exec("UPDATE acc_settings SET setting_value = ? WHERE setting_key = 'default_fiscal_year_id'", [$fiscalYearId]);
        } else {
            R::exec("INSERT INTO acc_settings (setting_key, setting_value, userid, created_at) VALUES ('default_fiscal_year_id', ?, ?, ?)",
                [$fiscalYearId, $userID, $today]);
        }

        header("location:accSetupController.php?do=sucess");
        exit;
    } catch (Exception $e) {
        header("location:accSetupController.php?do=error");
        exit;
    }
}

elseif ($do == "clearTemplates") {
    try {
        $clear_password = isset($_POST['clear_password']) ? $_POST['clear_password'] : '';

        if ($clear_password !== 'gt4') {
            $smarty->assign("clearTemplateError", 1);
            $setting = R::getRow("SELECT * FROM acc_settings WHERE setting_key = 'module_initialized' LIMIT 1");
            $isInitialized = (!empty($setting) && $setting['setting_value'] == '1');
            $smarty->assign("already_initialized", $isInitialized ? 1 : 0);
            if ($isInitialized) {
                $accountCount = R::getCell("SELECT COUNT(*) FROM acc_account WHERE del = 0");
                $journalCount = R::getCell("SELECT COUNT(*) FROM acc_journal_entry WHERE del = 0");
                $fyData = R::getRow("SELECT * FROM acc_fiscal_year WHERE del = 0 ORDER BY id DESC LIMIT 1");
                $smarty->assign("accountCount", $accountCount);
                $smarty->assign("journalCount", $journalCount);
                $smarty->assign("fyData", $fyData);
            }
            $smarty->display("accSetupview/setup.html");
        } else {
            // Clear all accounting module data (order matters for foreign keys)
            // NOTE: acc_account_template is NOT cleared - it's reference/seed data needed for re-initialization
            R::exec("DELETE FROM acc_journal_entry_line");
            R::exec("DELETE FROM acc_journal_entry");
            R::exec("DELETE FROM acc_opening_balance");
            R::exec("DELETE FROM acc_budget_line");
            R::exec("DELETE FROM acc_budget");
            R::exec("DELETE FROM acc_account");
            R::exec("DELETE FROM acc_cost_center");
            R::exec("DELETE FROM acc_fiscal_year");
            R::exec("DELETE FROM acc_settings");

            // Reset auto-increment
            R::exec("ALTER TABLE acc_journal_entry_line AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_journal_entry AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_opening_balance AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_budget_line AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_budget AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_account AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_cost_center AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_fiscal_year AUTO_INCREMENT = 1");
            R::exec("ALTER TABLE acc_settings AUTO_INCREMENT = 1");

            header("location:accSetupController.php?do=sucess");
            exit;
        }
    } catch (Exception $e) {
        header("location:accSetupController.php?do=error");
        exit;
    }
}

elseif ($do == "sucess") {
    $smarty->display("succes.html");
}

elseif ($do == "error") {
    $smarty->display("error.html");
}

if (!in_array($do, $ajaxActions)) {
    $smarty->display("footer.html");
}
?>
