<?php
namespace classs;
class AccountManager
{
    private $con;

    public function __construct($con)
    {
        $this->con = $con;
    }

    public function addAccount($postData)
    {
        // Extract data from the post data
        $lvacc = $postData['lvacc'];
        $idLevels = [];

        for ($i = 1; $i <= $lvacc; $i++) {
            $levelName = "lv" . $i;
            $idLevels[$levelName] = isset($postData[$levelName]) ? $postData[$levelName] : "";
        }

        $nameacc = $postData['nameacc'];
        $nature = $postData['nature'];
        $list_account = $postData['list_account'];

        // Validate The Form
        $formErrors = $this->validateForm($lvacc, $idLevels, $nameacc, $nature, $list_account);
        // Loop Into Errors Array And Echo It
        foreach ($formErrors as $error) {
            echo '<div class="alert alert-danger">' . $error . '</div>';
        }

        // Check If There's No Error Proceed The Update Operation
        if (empty($formErrors)) {
            $lvValues = $this->generateAccountValues($lvacc, $idLevels);

            // Insert Userinfo In Database
            $stmt = $this->con->prepare("INSERT INTO 
                                            level_acc(name_account, lev_acc, lv1, lv2, lv3, lv4, lv5, acc_up, nature_account, list_account, user_id_add, DateInsert)
                                        VALUES(:zname_account, :zlev_acc, :lv1, :lv2, :lv3, :lv4, :lv5, :acc_up, :znature_account, :zlist_account, :zuser_id_add, now()) ");
            $stmt->execute(
                array_merge([
                    'zname_account' => $nameacc,
                    'zlev_acc' => $lvacc,
                    'znature_account' => $nature,
                    'zlist_account' => $list_account,
                    'zuser_id_add' => $_SESSION['admin']
                ], $lvValues)
            );

            // Echo Success Message
            $theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' تمت الإضافة</div>';
            redirectlink($theMsg, '?Manage=tree&do=Manage', "شجرة الحسابات", 5);
        }
    }

    private function validateForm($lvacc, $idLevels, $nameacc, $nature, $list_account)
    {
        $formErrors = [];

        if (empty($nameacc)) {
            $formErrors[] = 'لا يجب أن يكون إسم الحساب  <strong>فارغ</strong>';
        }

        if (empty($nature)) {
            $formErrors[] = 'لا يجب أن يكون طبيعة  <strong>فارغ</strong>';
        }

        if (empty($list_account)) {
            $formErrors[] = 'لا يجب أن تكون القائمة المالية  <strong>فارغه</strong>';
        }

        for ($i = 1; $i <= $lvacc; $i++) {
            $levelName = "lv" . $i;
            $acc_up = $i > 1 ? $idLevels["lv" . ($i - 1)] : "";

            if (empty($idLevels[$levelName]) && $i != 5) {
                $formErrors[] = "يجب إدخال حساب المستوى $i";
            }
        }

        return $formErrors;
    }

    private function generateAccountValues($lvacc, $idLevels)
    {
        $lvValues = [
            'lv1' => 0,
            'lv2' => 0,
            'lv3' => 0,
            'lv4' => 0,
            'lv5' => 0,
            'acc_up' => ""
        ];

        for ($i = 1; $i <= $lvacc; $i++) {
            $levelName = "lv" . $i;
            $acc_up = $i > 1 ? $idLevels["lv" . ($i - 1)] : "";

            $stmt = $this->con->prepare("SELECT MAX($levelName) as last_code_account FROM level_acc where lev_acc = $i AND acc_up = :acc_up");
            $stmt->execute(['acc_up' => $acc_up]);
            $account1s = $stmt->fetchAll();

            foreach ($account1s as $key => $account1) {
                $last_code_account = $account1['last_code_account'];

                if (!empty($last_code_account)) {
                    $lvValues[$levelName] = $last_code_account + 1;
                } else {
                    if ($i > 1) {
                        $lvValues[$levelName] = $lvValues["lv" . ($i - 1)] + 1;
                    } else {
                        $lvValues[$levelName] = 1;
                    }
                }
            }
        }

        $lvValues['acc_up'] = $acc_up;

        return $lvValues;
    }
}

// Example of usage:

