<?php
/*
|--------------------------------------------------------------------------
| ACCOUNTMANAGER - حسابداری ساده مستقل
| File: simple_accounting.php
| Code ID: ACM-SIMPLE-003
| PHP: 7.4.33
|--------------------------------------------------------------------------
| تمام دادهها فقط در جداول simple_* ذخیره میشوند.
| اجرای فایل SQL با نام simple_accounting_schema.sql قبل از استفاده الزامی است.
*/
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/functions.php';
require_login();
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
$pdo = db();
$userId = (int) current_user_id();
$companyId = (int) ($_SESSION['acm_active_company_id'] ?? 0);
if ($companyId <= 0) { header('Location: companies.php'); exit; }
// اعتبارسنجی دسترسی به شرکت فعال، مطابق ساختار اصلی برنامه؛ بدون دسترسی به دادههای حسابداری اصلی.
if (is_super_admin()) {
$check = $pdo->prepare('SELECT id, company_name FROM companies WHERE id=? AND is_active=1 LIMIT 1');
$check->execute([$companyId]);
} else {
$check = $pdo->prepare('SELECT c.id,c.company_name FROM companies c INNER JOIN company_members cm ON cm.company_id=c.id WHERE c.id=? AND cm.user_id=? AND cm.is_active=1 AND c.is_active=1 LIMIT 1');
$check->execute([$companyId,$userId]);
}
$company = $check->fetch(PDO::FETCH_ASSOC);
if (!$company) { header('Location: companies.php'); exit; }
// ارتقای امن نسخه 003: فقط افزودن ساختارهای موردنیاز؛ هیچ داده یا جدول قبلی حذف/بازنویسی نمیشود.
$pdo->exec("CREATE TABLE IF NOT EXISTS simple_ledger_entries (
id INT NOT NULL AUTO_INCREMENT,
company_id INT NOT NULL,
person_id INT NOT NULL,
entry_type VARCHAR(40) NOT NULL,
ledger_effect ENUM('debit','credit') NOT NULL,
amount DECIMAL(18,2) NOT NULL DEFAULT 0,
entry_date DATE NOT NULL,
description TEXT NULL,
currency VARCHAR(10) NOT NULL DEFAULT 'IRR',
created_by INT NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_simple_ledger_company_person (company_id, person_id),
KEY idx_simple_ledger_date (entry_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$addressColumn = $pdo->query("SHOW COLUMNS FROM simple_persons LIKE 'address'")->fetch(PDO::FETCH_ASSOC);
if (!$addressColumn) {
$pdo->exec("ALTER TABLE simple_persons ADD COLUMN address VARCHAR(500) NULL AFTER mobile");
}
$operationEffects = [
'discount_to_customer' => 'credit',
'discount_from_supplier' => 'debit',
'debit_difference' => 'debit',
'credit_difference' => 'credit',
'old_sale' => 'debit',
'old_purchase' => 'credit'
];
$operationLabels = [
'receipt' => 'دریافت وجه',
'payment' => 'پرداخت وجه',
'discount_to_customer' => 'تخفیف به مشتری',
'discount_from_supplier' => 'تخفیف از فروشنده',
'debit_difference' => 'اختلاف حساب بدهکار',
'credit_difference' => 'اختلاف حساب بستانکار',
'old_sale' => 'فاکتور فروش قبلی',
'old_purchase' => 'فاکتور خرید قبلی'
];
if (empty($_SESSION['acm_simple_csrf'])) { $_SESSION['acm_simple_csrf'] = bin2hex(random_bytes(32)); }
$csrf = (string) $_SESSION['acm_simple_csrf'];
$error = '';
$success = (string)($_GET['msg'] ?? '');
function acmSimpleE($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function acmSimpleNum($v) {
$v = str_replace([',','٬','،',' '], '', (string)$v);
$v = str_replace(['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹','٠','١','٢','٣','٤','٥','٦','٧','٨','٩'], ['0','1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6','7','8','9'], $v);
return is_numeric($v) ? (float)$v : 0;
}
function acmSimpleMoney($v) { return number_format((float)$v, 0, '.', ','); }
function acmSimpleCurrencyLabel($c) { $m=['IRR'=>'ریال','TOMAN'=>'تومان','USD'=>'دلار','EUR'=>'یورو','TRY'=>'لیر','AED'=>'درهم','GBP'=>'پوند','CHF'=>'فرانک','CNY'=>'یوان','RUB'=>'روبل']; return $m[$c]??$c; }
function acmSimpleExcel($filename,$title,$headers,$rows) {
header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.$filename.'.xls"; filename*=UTF-8\'\''.rawurlencode($filename).'.xls');
echo "\xEF\xBB\xBF";
echo '<!doctype html><html lang="fa" dir="rtl"><head><meta charset="utf-8"><style>body{direction:rtl;font-family:Tahoma;text-align:right}table{border-collapse:collapse;width:100%;direction:rtl}th,td{border:1px solid #333;padding:7px;text-align:right;mso-number-format:"\@"}th{background:#dce8f5;font-weight:bold}.title{font-size:16px;font-weight:bold;margin:10px 0}
.invoice-paper{max-width:1100px;margin:18px auto;padding:28px;color:#172536;font-size:13px;border:1px solid #c8d0d9}.invoice-head{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid #253b52;padding-bottom:14px;margin-bottom:16px}.invoice-head h2{font-size:20px;margin:0 0 8px}.invoice-head h3{font-size:16px;margin:0 0 6px}.invoice-meta{line-height:2.1;text-align:left}.party-box{padding:11px 13px;border:1px solid #aeb9c5;background:#f8fafc;margin-bottom:15px}.party-box span{margin-right:25px}.invoice-table{min-width:850px;border-collapse:collapse}.invoice-table th,.invoice-table td,.invoice-entry-table th,.invoice-entry-table td{border:1px solid #6f7d8b!important;padding:8px;text-align:center;white-space:normal}.invoice-table th,.invoice-entry-table th{background:#eaf0f6!important;color:#182b3e}.invoice-table td:nth-child(2){text-align:right;min-width:180px}.invoice-summary{width:min(470px,100%);margin:16px 0 12px auto;border:1px solid #8795a3}.invoice-summary>div{display:flex;justify-content:space-between;padding:8px 12px;border-bottom:1px solid #c5cdd5}.invoice-summary>div:last-child{border-bottom:0}.invoice-summary .grand{background:#eaf0f6;font-size:16px;font-weight:bold}.invoice-summary .remaining{background:#f5f8fb;font-weight:bold}.words-box{border:1px solid #8795a3;background:#f8fafc;padding:12px;margin:12px 0;font-size:14px;line-height:2}.invoice-description{border:1px solid #c5cdd5;padding:10px;min-height:42px}.signature-row{display:flex;justify-content:space-between;margin-top:48px;padding:0 25px}.signature-row div{width:35%;text-align:center;border-top:1px solid #667;padding-top:8px}.invoice-section-title{display:flex;justify-content:space-between;align-items:center;margin:12px 0}.invoice-entry-table{min-width:1000px}.invoice-entry-table input,.invoice-entry-table select{min-width:75px;padding:7px}.invoice-entry-table td:nth-child(2){min-width:220px}.desc-cell{display:grid;gap:5px}.line-no{font-weight:bold}.gross-cell,.net-cell{font-weight:bold;font-variant-numeric:tabular-nums}.remove-line{border:0;background:#ffeded;color:#a22;border-radius:5px;padding:6px 10px;cursor:pointer}.invoice-live-summary{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;background:#f5f8fc;border:1px solid #d5e0eb;padding:12px;border-radius:9px;margin:14px 0}.invoice-live-summary>div:not(.words-box){display:flex;justify-content:space-between;gap:8px;padding:7px;border-bottom:1px solid #dbe3eb}.invoice-live-summary .grand,.invoice-live-summary .remaining{font-weight:bold;color:#174d7d}.invoice-live-summary .words-box{grid-column:1/-1;margin:0}.money-unit{display:inline-block;margin-right:7px;color:#65788c;font-size:11px}.invoice-bottom{margin-top:12px}.invoice-fields{grid-template-columns:repeat(3,minmax(0,1fr))}.print-actions{display:flex;gap:8px;justify-content:center;margin:15px}
@media(max-width:850px){.invoice-fields{grid-template-columns:repeat(2,minmax(0,1fr))}.invoice-live-summary{grid-template-columns:1fr 1fr}}
@media(max-width:560px){.invoice-fields,.invoice-live-summary{grid-template-columns:1fr}.invoice-paper{padding:12px}.invoice-head{gap:8px}.invoice-head h2{font-size:16px}.invoice-meta{font-size:11px}}
@media print{body.print-ledger .wrap>*:not(#ledger){display:none!important}body.print-persons .wrap>*:not(#lists){display:none!important}body.print-persons #lists{display:block!important}body.print-persons #lists .no-print{display:none!important}body.print-persons #lists table,body.print-ledger #ledger table{min-width:0;width:100%;font-size:10px}body{font-size:11px!important}.invoice-paper{max-width:none;padding:8mm;border:0;margin:0}.invoice-table{min-width:0;width:100%}.invoice-table th,.invoice-table td{padding:5px;font-size:10px}.invoice-summary{break-inside:avoid}.words-box,.party-box{break-inside:avoid}.signature-row{margin-top:35px}.tablewrap{overflow:visible}}
</style></head><body><div class="title">'.acmSimpleE($title).'</div><table><thead><tr>';
foreach($headers as $h) echo '<th>'.acmSimpleE($h).'</th>';
echo '</tr></thead><tbody>';
foreach($rows as $row){echo '<tr>';foreach($row as $cell)echo '<td>'.acmSimpleE($cell).'</td>';echo '</tr>';}
echo '</tbody></table></body></html>