<?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('getNextEntryNo');

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

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

//check and use the condition that suits this action
if (empty($do)) {
    header("location:accJournalController.php?do=show");
}

elseif ($do == "show") {
    $fiscal_year_id = isset($_GET['fiscal_year_id']) ? (int)$_GET['fiscal_year_id'] : 0;

    $where = "WHERE j.del = 0";
    $params = array();
    if ($fiscal_year_id > 0) {
        $where .= " AND j.fiscal_year_id = ?";
        $params[] = $fiscal_year_id;
    }

    $entries = R::getAll("SELECT j.*, fy.name as fiscal_year_name
        FROM acc_journal_entry j
        LEFT JOIN acc_fiscal_year fy ON j.fiscal_year_id = fy.id
        $where ORDER BY j.entry_date DESC, j.id DESC", $params);

    $fiscalYears = R::getAll("SELECT * FROM acc_fiscal_year WHERE del = 0 ORDER BY start_date DESC");

    $smarty->assign("entries", $entries);
    $smarty->assign("fiscalYears", $fiscalYears);
    $smarty->assign("selectedFiscalYear", $fiscal_year_id);
    $smarty->display("accJournalview/list.html");
}

elseif ($do == "add") {
    $accounts = R::getAll("SELECT id, code, name FROM acc_account WHERE is_leaf = 1 AND del = 0 ORDER BY code ASC");
    $costcenters = R::getAll("SELECT * FROM acc_cost_center WHERE del = 0 ORDER BY name ASC");
    $fiscalYears = R::getAll("SELECT * FROM acc_fiscal_year WHERE del = 0 AND is_closed = 0 ORDER BY start_date DESC");

    // Get default fiscal year
    $defaultFY = R::getRow("SELECT setting_value FROM acc_settings WHERE setting_key = 'default_fiscal_year_id' LIMIT 1");
    $defaultFYId = !empty($defaultFY) ? $defaultFY['setting_value'] : 0;

    // Get next entry number for default fiscal year
    $lastEntry = R::getRow("SELECT MAX(entry_no) as max_no FROM acc_journal_entry WHERE fiscal_year_id = ? AND del = 0", [$defaultFYId]);
    $nextEntryNumber = (!empty($lastEntry['max_no'])) ? (int)$lastEntry['max_no'] + 1 : 1;

    $smarty->assign("accounts", $accounts);
    $smarty->assign("costcenters", $costcenters);
    $smarty->assign("fiscalYears", $fiscalYears);
    $smarty->assign("defaultFY", $defaultFYId);
    $smarty->assign("nextEntryNumber", $nextEntryNumber);
    $smarty->display("accJournalview/add.html");
}

elseif ($do == "savedata") {
    try {
        $entry_date = isset($_POST['entry_date']) ? $_POST['entry_date'] : date("Y-m-d");
        $fiscal_year_id = isset($_POST['fiscal_year_id']) ? (int)$_POST['fiscal_year_id'] : 0;
        $description = isset($_POST['description']) ? trim($_POST['description']) : '';
        // Line arrays (indexed format: lines[0][account_id], lines[0][debit], etc.)
        $lines = isset($_POST['lines']) ? $_POST['lines'] : array();
        $attachmentName1 = null;
        if (!empty($_FILES['attachment']['name'])) {
            $uploadDir = "../uploads/attachments/"; 
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            $fileExt = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);
            $attachmentName1 = "journal_" . time() . "_" . uniqid() . "." . $fileExt;
            move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadDir . $attachmentName1);
        }
        $attachmentName2 = null;
        if (!empty($_FILES['attachment2']['name'])) {
            $uploadDir = "../uploads/attachments/"; 
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            $fileExt = pathinfo($_FILES['attachment2']['name'], PATHINFO_EXTENSION);
            $attachmentName2 = "journal_" . time() . "_" . uniqid() . "." . $fileExt;
            move_uploaded_file($_FILES['attachment2']['tmp_name'], $uploadDir . $attachmentName2);
        }
        // Calculate totals and validate
        $totalDebit = 0;
        $totalCredit = 0;
        $validLines = array();
        foreach ($lines as $line) {
            if (empty($line['account_id'])) continue;
            $d = (float)$line['debit'];
            $c = (float)$line['credit'];
            $totalDebit += $d;
            $totalCredit += $c;
            $validLines[] = $line;
        }

        if (round($totalDebit, 2) != round($totalCredit, 2) || $totalDebit == 0) {
            header("location:accJournalController.php?do=error");
            exit;
        }

        // Auto-generate entry number
        $lastEntry = R::getRow("SELECT MAX(entry_no) as max_no FROM acc_journal_entry WHERE fiscal_year_id = ? AND del = 0", [$fiscal_year_id]);
        $entry_no = (!empty($lastEntry['max_no'])) ? (int)$lastEntry['max_no'] + 1 : 1;

        // Save journal header using raw SQL
        R::exec("INSERT INTO acc_journal_entry (entry_no, entry_date, fiscal_year_id, description, total_debit, total_credit, is_reversed, is_opening, userid, created_at, del, attachment_file1, attachment_file2) VALUES (?, ?, ?, ?, ?, ?, 0, 0, ?, ?, 0, ?, ?)",
            [$entry_no, $entry_date, $fiscal_year_id, $description, $totalDebit, $totalCredit, $userID, $today, $attachmentName1, $attachmentName2]);
        $journalId = R::getCell("SELECT LAST_INSERT_ID()");

        // Save journal lines and update account balances
        foreach ($validLines as $line) {
            $debitAmt = (float)$line['debit'];
            $creditAmt = (float)$line['credit'];
            $lineDesc = isset($line['description']) ? trim($line['description']) : '';
            $ccId = isset($line['costcenter_id']) ? (int)$line['costcenter_id'] : 0;
            $accId = (int)$line['account_id'];

            R::exec("INSERT INTO acc_journal_entry_line (journal_entry_id, account_id, debit, credit, description, cost_center_id) VALUES (?, ?, ?, ?, ?, ?)",
                [$journalId, $accId, $debitAmt, $creditAmt, $lineDesc, $ccId]);

            // Update account balance
            $netAmount = $debitAmt - $creditAmt;
            R::exec("UPDATE acc_account SET balance = balance + ? WHERE id = ?", [$netAmount, $accId]);
        }

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

elseif ($do == "view") {
    $id = (int)$_GET['id'];
    $journal = R::getRow("SELECT j.*, fy.name as fiscal_year_name FROM acc_journal_entry j LEFT JOIN acc_fiscal_year fy ON j.fiscal_year_id = fy.id WHERE j.id = ? AND j.del = 0", [$id]);
    $lines = R::getAll("SELECT jl.*, a.code as account_code, a.name as account_name, cc.name as costcenter_name
        FROM acc_journal_entry_line jl
        LEFT JOIN acc_account a ON jl.account_id = a.id
        LEFT JOIN acc_cost_center cc ON jl.cost_center_id = cc.id
        WHERE jl.journal_entry_id = ? ORDER BY jl.id ASC", [$id]);

    $smarty->assign("journal", $journal);
    $smarty->assign("lines", $lines);
    $smarty->display("accJournalview/view.html");
}

elseif ($do == "reverse") {
    try {
        $id = (int)$_GET['id'];
        $original = R::getRow("SELECT * FROM acc_journal_entry WHERE id = ? AND del = 0 AND is_reversed = 0", [$id]);

        if (empty($original)) {
            header("location:accJournalController.php?do=error");
            exit;
        }

        $originalLines = R::getAll("SELECT * FROM acc_journal_entry_line WHERE journal_entry_id = ?", [$id]);

        // Auto-generate entry number
        $lastEntry = R::getRow("SELECT MAX(entry_no) as max_no FROM acc_journal_entry WHERE fiscal_year_id = ? AND del = 0", [$original['fiscal_year_id']]);
        $entry_no = (!empty($lastEntry['max_no'])) ? (int)$lastEntry['max_no'] + 1 : 1;

        // Create reversal journal
        R::exec("INSERT INTO acc_journal_entry (entry_no, entry_date, fiscal_year_id, description, total_debit, total_credit, is_reversed, reversed_entry_id, is_opening, userid, created_at, del) VALUES (?, ?, ?, ?, ?, ?, 0, ?, 0, ?, ?, 0)",
            [$entry_no, date("Y-m-d"), $original['fiscal_year_id'], 'عكس قيد رقم ' . $original['entry_no'] . ' - ' . $original['description'], $original['total_debit'], $original['total_credit'], $id, $userID, $today]);
        $reversalId = R::getCell("SELECT LAST_INSERT_ID()");

        // Create reversed lines (swap debit/credit)
        foreach ($originalLines as $origLine) {
            R::exec("INSERT INTO acc_journal_entry_line (journal_entry_id, account_id, debit, credit, description, cost_center_id) VALUES (?, ?, ?, ?, ?, ?)",
                [$reversalId, $origLine['account_id'], $origLine['credit'], $origLine['debit'], $origLine['description'], $origLine['cost_center_id']]);

            // Reverse the balance effect
            $netAmount = $origLine['credit'] - $origLine['debit'];
            R::exec("UPDATE acc_account SET balance = balance + ? WHERE id = ?", [$netAmount, $origLine['account_id']]);
        }

        // Mark original as reversed
        R::exec("UPDATE acc_journal_entry SET is_reversed = 1, userid = ?, created_at = ? WHERE id = ?", [$userID, $today, $id]);

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

elseif ($do == "delete") {
    try {
        $id = (int)$_GET['id'];

        // Reverse account balance effects
        $lines = R::getAll("SELECT * FROM acc_journal_entry_line WHERE journal_entry_id = ?", [$id]);
        foreach ($lines as $line) {
            $netAmount = $line['credit'] - $line['debit'];
            R::exec("UPDATE acc_account SET balance = balance + ? WHERE id = ?", [$netAmount, $line['account_id']]);
        }

        // Soft delete journal and lines
        R::exec("UPDATE acc_journal_entry SET del = 1, userid = ?, created_at = ? WHERE id = ?", [$userID, $today, $id]);
        R::exec("DELETE FROM acc_journal_entry_line WHERE journal_entry_id = ?", [$id]);

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

elseif ($do == "getNextEntryNo") {
    $fiscal_year_id = isset($_GET['fiscal_year_id']) ? (int)$_GET['fiscal_year_id'] : 0;
    $lastEntry = R::getRow("SELECT MAX(entry_no) as max_no FROM acc_journal_entry WHERE fiscal_year_id = ? AND del = 0", [$fiscal_year_id]);
    $nextNo = (!empty($lastEntry['max_no'])) ? (int)$lastEntry['max_no'] + 1 : 1;
    echo json_encode(array('status' => 1, 'entry_no' => $nextNo));
    exit;
}

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

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

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