<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_permission('assets.manage');require __DIR__.'/app/layout.php';
$pdo=db();$companyId=company_id();$userId=(int)user()['id'];$currencyId=(int)scalar('SELECT base_currency_id FROM companies WHERE id=?',[$companyId]);
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();try{$action=(string)($_POST['action']??'');
 if($action==='category_create'){$s=$pdo->prepare("INSERT INTO asset_categories(company_id,code,name_ar,asset_account_id,accumulated_depreciation_account_id,depreciation_expense_account_id,default_method,default_useful_life_months,default_residual_pct,is_active) VALUES (?,?,?,?,?,?,'straight_line',?,?,1)");$s->execute([$companyId,trim((string)$_POST['code']),trim((string)$_POST['name_ar']),(int)$_POST['asset_account_id'],(int)$_POST['accumulated_account_id'],(int)$_POST['expense_account_id'],(int)$_POST['useful_life_months'],(float)$_POST['residual_pct']]);audit('asset_category.create','asset_category',(string)$pdo->lastInsertId());flash('success','تم إنشاء تصنيف الأصل.');
 }elseif($action==='asset_create'){$cost=round((float)$_POST['acquisition_cost'],2);$residual=round((float)$_POST['residual_value'],2);if($cost<=0||$residual>$cost)throw new RuntimeException('تحقق من تكلفة الأصل والقيمة التخريدية.');$s=$pdo->prepare("INSERT INTO assets(company_id,branch_id,asset_category_id,asset_no,name_ar,serial_no,manufacturer,model,purchase_date,capitalization_date,currency_id,acquisition_cost,residual_value,depreciation_method,useful_life_months,net_book_value,current_project_id,current_location,asset_status,is_equipment,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,'straight_line',?,?,?,?, 'active',?,NOW(),NOW())");$s->execute([$companyId,(int)user()['branch_id'],(int)$_POST['category_id'],trim((string)$_POST['asset_no']),trim((string)$_POST['name_ar']),trim((string)($_POST['serial_no']??''))?:null,trim((string)($_POST['manufacturer']??''))?:null,trim((string)($_POST['model']??''))?:null,($_POST['purchase_date']??'')?:null,$_POST['capitalization_date'],$currencyId,$cost,$residual,(int)$_POST['useful_life_months'],$cost,(int)($_POST['project_id']??0)?:null,trim((string)($_POST['location']??''))?:null,isset($_POST['is_equipment'])?1:0]);audit('asset.create','asset',(string)$pdo->lastInsertId());flash('success','تم تسجيل الأصل.');
 }elseif($action==='depreciation_calculate'){$periodId=(int)$_POST['fiscal_period_id'];$period=$pdo->prepare("SELECT fp.* FROM fiscal_periods fp JOIN fiscal_years fy ON fy.id=fp.fiscal_year_id WHERE fp.id=? AND fy.company_id=? AND fp.status='open'");$period->execute([$periodId,$companyId]);$period=$period->fetch();if(!$period)throw new RuntimeException('الفترة غير صالحة أو مقفلة.');$exists=(int)scalar('SELECT COUNT(*) FROM depreciation_runs WHERE company_id=? AND fiscal_period_id=?',[$companyId,$periodId]);if($exists)throw new RuntimeException('تم احتساب إهلاك هذه الفترة مسبقًا.');$assets=$pdo->prepare("SELECT * FROM assets WHERE company_id=? AND asset_status IN ('active','idle') AND depreciation_method='straight_line' AND useful_life_months>0 AND net_book_value>residual_value AND capitalization_date<=? AND deleted_at IS NULL");$assets->execute([$companyId,$period['ends_on']]);$assets=$assets->fetchAll();$pdo->beginTransaction();$runNo='DEP-'.date('Ym',strtotime($period['ends_on']));$pdo->prepare("INSERT INTO depreciation_runs(company_id,fiscal_period_id,run_no,run_date,status,total_amount,prepared_by,created_at) VALUES (?,?,?,?, 'calculated',0,?,NOW())")->execute([$companyId,$periodId,$runNo,$period['ends_on'],$userId]);$runId=(int)$pdo->lastInsertId();$line=$pdo->prepare('INSERT INTO depreciation_run_lines(depreciation_run_id,asset_id,project_id,opening_net_book_value,depreciation_amount,closing_net_book_value) VALUES (?,?,?,?,?,?)');$total=0;foreach($assets as $a){$monthly=round(((float)$a['acquisition_cost']-(float)$a['residual_value'])/(int)$a['useful_life_months'],2);$amount=min($monthly,(float)$a['net_book_value']-(float)$a['residual_value']);if($amount<=0)continue;$closing=(float)$a['net_book_value']-$amount;$line->execute([$runId,$a['id'],$a['current_project_id'],$a['net_book_value'],$amount,$closing]);$total+=$amount;}$pdo->prepare('UPDATE depreciation_runs SET total_amount=? WHERE id=?')->execute([$total,$runId]);$pdo->commit();audit('depreciation.calculate','depreciation_run',(string)$runId,['total'=>$total]);flash('success','تم احتساب الإهلاك بمبلغ '.number_format($total,2));
 }elseif($action==='depreciation_post'){$runId=(int)$_POST['id'];$run=$pdo->prepare("SELECT * FROM depreciation_runs WHERE id=? AND company_id=? AND status='calculated'");$run->execute([$runId,$companyId]);$run=$run->fetch();if(!$run)throw new RuntimeException('تشغيل الإهلاك غير صالح.');$pdo->beginTransaction();$lines=$pdo->prepare('SELECT * FROM depreciation_run_lines WHERE depreciation_run_id=?');$lines->execute([$runId]);foreach($lines->fetchAll() as $l)$pdo->prepare('UPDATE assets SET accumulated_depreciation=accumulated_depreciation+?,net_book_value=? WHERE id=? AND company_id=?')->execute([$l['depreciation_amount'],$l['closing_net_book_value'],$l['asset_id'],$companyId]);$pdo->prepare("UPDATE depreciation_runs SET status='posted',reviewed_by=?,posted_at=NOW() WHERE id=?")->execute([$userId,$runId]);$pdo->commit();audit('depreciation.post','depreciation_run',(string)$runId);flash('success','تم اعتماد الإهلاك وتحديث القيم الدفترية.');
 }}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e instanceof PDOException?'الرقم مكرر أو البيانات غير صالحة.':$e->getMessage());}redirect('assets.php');}
$accounts=$pdo->prepare("SELECT id,code,name_ar FROM accounts WHERE company_id=? AND is_postable=1 AND status='active' ORDER BY code");$accounts->execute([$companyId]);$accounts=$accounts->fetchAll();$categories=$pdo->prepare('SELECT * FROM asset_categories WHERE company_id=? AND is_active=1 ORDER BY code');$categories->execute([$companyId]);$categories=$categories->fetchAll();$projects=$pdo->prepare('SELECT id,project_no,name_ar FROM projects WHERE company_id=? AND deleted_at IS NULL ORDER BY project_no');$projects->execute([$companyId]);$projects=$projects->fetchAll();$periods=$pdo->prepare("SELECT fp.id,fp.name,fy.name year_name FROM fiscal_periods fp JOIN fiscal_years fy ON fy.id=fp.fiscal_year_id WHERE fy.company_id=? AND fp.status='open' ORDER BY fp.starts_on");$periods->execute([$companyId]);$periods=$periods->fetchAll();$assets=$pdo->prepare("SELECT a.*,ac.name_ar category_name,p.name_ar project_name FROM assets a JOIN asset_categories ac ON ac.id=a.asset_category_id LEFT JOIN projects p ON p.id=a.current_project_id WHERE a.company_id=? AND a.deleted_at IS NULL ORDER BY a.asset_no");$assets->execute([$companyId]);$assets=$assets->fetchAll();$runs=$pdo->prepare('SELECT dr.*,fp.name period_name FROM depreciation_runs dr JOIN fiscal_periods fp ON fp.id=dr.fiscal_period_id WHERE dr.company_id=? ORDER BY dr.id DESC');$runs->execute([$companyId]);$runs=$runs->fetchAll();
render_header('assets','الأصول والمعدات','سجل الأصول وربط المعدات بالمشاريع واحتساب الإهلاك.');?>
<details class="panel quick-add"><summary>＋ تصنيف أصل</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="category_create"><div class="form-grid"><label>الكود<input name="code" required></label><label>الاسم<input name="name_ar" required></label><?php foreach([['asset_account_id','حساب الأصل'],['accumulated_account_id','مجمع الإهلاك'],['expense_account_id','مصروف الإهلاك']] as [$field,$label]):?><label><?= e($label) ?><select name="<?= e($field) ?>"><?php foreach($accounts as $a):?><option value="<?= (int)$a['id'] ?>"><?= e($a['code'].' — '.$a['name_ar']) ?></option><?php endforeach;?></select></label><?php endforeach;?><label>العمر بالأشهر<input type="number" min="1" name="useful_life_months" value="60"></label><label>القيمة التخريدية %<input type="number" step="0.01" name="residual_pct" value="0"></label></div><button class="primary-btn">حفظ التصنيف</button></form></details>
<details class="panel quick-add" open><summary>＋ أصل أو معدة</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="asset_create"><div class="form-grid"><label>التصنيف<select name="category_id"><?php foreach($categories as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['code'].' — '.$c['name_ar']) ?></option><?php endforeach;?></select></label><label>رقم الأصل<input name="asset_no" required></label><label>اسم الأصل<input name="name_ar" required></label><label>الرقم التسلسلي<input name="serial_no"></label><label>المصنع<input name="manufacturer"></label><label>الموديل<input name="model"></label><label>تاريخ الشراء<input type="date" name="purchase_date"></label><label>تاريخ الرسملة<input type="date" name="capitalization_date" value="<?= date('Y-m-d') ?>"></label><label>التكلفة<input type="number" step="0.01" name="acquisition_cost" required></label><label>القيمة التخريدية<input type="number" step="0.01" name="residual_value" value="0"></label><label>العمر بالأشهر<input type="number" min="1" name="useful_life_months" value="60"></label><label>المشروع<select name="project_id"><option value="0">غير مرتبط</option><?php foreach($projects as $p):?><option value="<?= (int)$p['id'] ?>"><?= e($p['project_no'].' — '.$p['name_ar']) ?></option><?php endforeach;?></select></label><label>الموقع<input name="location"></label><label class="checks"><span><input type="checkbox" name="is_equipment"> معدة تشغيلية</span></label></div><button class="primary-btn">تسجيل الأصل</button></form></details>
<section class="panel form-card"><header><h2>إهلاك الفترة</h2></header><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="depreciation_calculate"><label>الفترة المفتوحة<select name="fiscal_period_id"><?php foreach($periods as $p):?><option value="<?= (int)$p['id'] ?>"><?= e($p['year_name'].' — '.$p['name']) ?></option><?php endforeach;?></select></label><button class="primary-btn">احتساب الإهلاك</button></form><div class="responsive-table"><table><thead><tr><th>التشغيل</th><th>الفترة</th><th>المبلغ</th><th>الحالة</th><th></th></tr></thead><tbody><?php foreach($runs as $r):?><tr><td><?= e($r['run_no']) ?></td><td><?= e($r['period_name']) ?></td><td><?= number_format((float)$r['total_amount'],2) ?></td><td><?= e($r['status']) ?></td><td><?php if($r['status']==='calculated'):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="depreciation_post"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button>اعتماد</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<section class="panel data-card"><header><h2>سجل الأصول</h2></header><div class="responsive-table"><table><thead><tr><th>الأصل</th><th>التصنيف</th><th>المشروع</th><th>التكلفة</th><th>مجمع الإهلاك</th><th>صافي القيمة</th><th>الحالة</th></tr></thead><tbody><?php foreach($assets as $a):?><tr><td><?= e($a['asset_no'].' — '.$a['name_ar']) ?></td><td><?= e($a['category_name']) ?></td><td><?= e($a['project_name']?:'—') ?></td><td><?= number_format((float)$a['acquisition_cost'],2) ?></td><td><?= number_format((float)$a['accumulated_depreciation'],2) ?></td><td><?= number_format((float)$a['net_book_value'],2) ?></td><td><span class="chip"><?= e($a['asset_status']) ?></span></td></tr><?php endforeach;?></tbody></table></div></section>
<?php render_footer();
