<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_login();
require_once __DIR__ . '/../app/Services/AccountingService.php';

$pdo = db();
$cid = (int)$_SESSION['company_id'];
$uid = (int)($_SESSION['user_id'] ?? 0);
$svc = new AccountingService($pdo);

$msg = $_GET['msg'] ?? null;
$err = null;

$year = (int)($_GET['year'] ?? date('Y'));
$month = (int)($_GET['month'] ?? (int)date('m'));

$salaryExpId = account_id_by_code($pdo, $cid, '5310');
$salaryPayId = account_id_by_code($pdo, $cid, '2160');
$advAccId    = account_id_by_code($pdo, $cid, '1130');

if(!$salaryExpId || !$salaryPayId) {
  $err = 'تأكد من وجود حسابات: مصروف الرواتب (5310) و رواتب مستحقة (2160) في شجرة الحسابات.';
}

// Create payroll run
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='generate' && !$err) {
  $year = (int)($_POST['year'] ?? $year);
  $month = (int)($_POST['month'] ?? $month);
  $run_date = $_POST['run_date'] ?? date('Y-m-d');

  $pdo->beginTransaction();
  try {
    $st = $pdo->prepare("INSERT INTO payroll_runs (company_id, period_year, period_month, run_date, status) VALUES (?,?,?,?, 'DRAFT')
                         ON DUPLICATE KEY UPDATE run_date=VALUES(run_date)");
    $st->execute([$cid,$year,$month,$run_date]);

    $st = $pdo->prepare("SELECT id FROM payroll_runs WHERE company_id=? AND period_year=? AND period_month=?");
    $st->execute([$cid,$year,$month]);
    $payrollId = (int)$st->fetchColumn();

    // clear lines
    $pdo->prepare("DELETE FROM payroll_lines WHERE company_id=? AND payroll_id=?")->execute([$cid,$payrollId]);

    $emps = $pdo->prepare("SELECT id, full_name, salary_monthly FROM employees WHERE company_id=? AND status='ACTIVE'");
    $emps->execute([$cid]);
    $emps = $emps->fetchAll(PDO::FETCH_ASSOC);

    $ins = $pdo->prepare("INSERT INTO payroll_lines (company_id, payroll_id, employee_id, base_salary, additions, deductions, advances_deduction, net_salary)
                          VALUES (?,?,?,?,?,?,?,?)");

    foreach($emps as $e){
      $base = (float)$e['salary_monthly'];
      // Deduct advances: remaining open advances for employee up to end of month (simple: sum open advances - settled)
      $st = $pdo->prepare("
        SELECT IFNULL(SUM(a.amount),0) - IFNULL((
          SELECT SUM(s.amount) FROM employee_advance_settlements s 
          JOIN employee_advances aa ON aa.id=s.advance_id AND aa.company_id=s.company_id
          WHERE s.company_id=? AND aa.employee_id=? AND aa.status='OPEN'
        ),0) AS rem
        FROM employee_advances a
        WHERE a.company_id=? AND a.employee_id=? AND a.status='OPEN'
      ");
      $st->execute([$cid,(int)$e['id'],$cid,(int)$e['id']]);
      $rem = (float)$st->fetchColumn();
      $advDed = max(0.0, min($rem, $base)); // cap

      $net = $base - $advDed;
      $ins->execute([$cid,$payrollId,(int)$e['id'],$base,0,0,$advDed,$net]);
    }

    $pdo->commit();
    flash_set('تم توليد الرواتب بنجاح');
    header('Location: payroll.php?year='.$year.'&month='.$month);
    exit;
  } catch(Throwable $e){
    $pdo->rollBack();
    $err = $e->getMessage();
  }
}

// Post payroll to journal
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='post' && !$err) {
  $payrollId = (int)($_POST['payroll_id'] ?? 0);
  $st = $pdo->prepare("SELECT * FROM payroll_runs WHERE id=? AND company_id=?");
  $st->execute([$payrollId,$cid]);
  $run = $st->fetch(PDO::FETCH_ASSOC);
  if(!$run) $err='الدورة غير موجودة';
  if($run && $run['status']==='POSTED') $err='تم ترحيل الرواتب بالفعل';

  if(!$err){
    $lines = $pdo->prepare("SELECT pl.*, e.full_name FROM payroll_lines pl JOIN employees e ON e.id=pl.employee_id
                            WHERE pl.company_id=? AND pl.payroll_id=?");
    $lines->execute([$cid,$payrollId]);
    $lines = $lines->fetchAll(PDO::FETCH_ASSOC);
    $totalNet = 0.0;
    $totalAdvDed = 0.0;
    $totalBase = 0.0;
    foreach($lines as $l){
      $totalNet += (float)$l['net_salary'];
      $totalAdvDed += (float)$l['advances_deduction'];
      $totalBase += (float)$l['base_salary'];
    }

    $pdo->beginTransaction();
    try {
      // Journal: Dr Salaries Expense totalBase, Cr Salaries Payable totalNet, Cr Employee Advances totalAdvDed (reduces advance receivable)
      $jLines = [
        ['account_id'=>$salaryExpId,'debit'=>$totalBase,'credit'=>0,'description'=>'مصروف رواتب'],
        ['account_id'=>$salaryPayId,'debit'=>0,'credit'=>$totalNet,'description'=>'رواتب مستحقة'],
      ];
      if($totalAdvDed > 0.0001 && $advAccId){
        $jLines[] = ['account_id'=>$advAccId,'debit'=>0,'credit'=>$totalAdvDed,'description'=>'خصم عهد من الرواتب'];
      }
      $ref = sprintf('PAY-%04d-%02d', (int)$run['period_year'], (int)$run['period_month']);
      $svc->createManualJournal($cid, (string)$run['run_date'], $ref, 'ترحيل الرواتب', $jLines, $uid, 'PAYROLL', $payrollId);

      $pdo->prepare("UPDATE payroll_runs SET status='POSTED' WHERE id=? AND company_id=?")->execute([$payrollId,$cid]);
      $pdo->commit();
      flash_set('تم ترحيل الرواتب وإضافة القيد بنجاح');
      header('Location: payroll.php?year='.$run['period_year'].'&month='.$run['period_month']);
      exit;
    } catch(Throwable $e){
      $pdo->rollBack();
      $err = $e->getMessage();
    }
  }
}

$run = $pdo->prepare("SELECT * FROM payroll_runs WHERE company_id=? AND period_year=? AND period_month=?");
$run->execute([$cid,$year,$month]);
$run = $run->fetch(PDO::FETCH_ASSOC);

$lines = [];
if($run){
  $st = $pdo->prepare("SELECT pl.*, e.full_name FROM payroll_lines pl JOIN employees e ON e.id=pl.employee_id
                       WHERE pl.company_id=? AND pl.payroll_id=? ORDER BY e.full_name");
  $st->execute([$cid,(int)$run['id']]);
  $lines = $st->fetchAll(PDO::FETCH_ASSOC);
}

render_layout('الرواتب','الموارد البشرية <span class="mx-1">/</span> الرواتب', function() use ($year,$month,$run,$lines,$msg,$err) {
?>
<div class="container-fluid mt-3">
  <div class="d-flex align-items-start align-items-md-center justify-content-between flex-column flex-md-row gap-2">
    <div>
      <div class="fw-bold fs-4">الرواتب</div>
      <div class="text-secondary small">توليد الرواتب للشهر وترحيلها (قيد تلقائي)</div>
    </div>
  </div>

  <?php if($msg==='generated'): ?><div class="alert alert-success mt-3">تم توليد الرواتب</div><?php endif; ?>
  <?php if($msg==='posted'): ?><div class="alert alert-success mt-3">تم ترحيل الرواتب وإضافة القيد</div><?php endif; ?>
  <?php if($err): ?><div class="alert alert-danger mt-3"><?= h($err) ?></div><?php endif; ?>

  <div class="card cardx p-3 mt-2">
    <form method="post" class="row g-2 align-items-end">
      <input type="hidden" name="action" value="generate">
      <div class="col-6 col-md-2">
        <label class="form-label">السنة</label>
        <input class="form-control" type="number" name="year" value="<?= (int)$year ?>">
      </div>
      <div class="col-6 col-md-2">
        <label class="form-label">الشهر</label>
        <input class="form-control" type="number" name="month" min="1" max="12" value="<?= (int)$month ?>">
      </div>
      <div class="col-12 col-md-3">
        <label class="form-label">تاريخ الترحيل</label>
        <?= render_date_input('run_date', date('Y-m-d')) ?>
      </div>
      <div class="col-12 col-md-5 d-flex gap-2">
        <button class="btn btn-dark w-100"><i class="bi bi-gear"></i> توليد</button>
      </div>
    </form>
    <?php if($run && $run['status']==='DRAFT'): ?>
      <form method="post" class="mt-2">
        <input type="hidden" name="action" value="post">
        <input type="hidden" name="payroll_id" value="<?= (int)$run['id'] ?>">
        <button class="btn btn-outline-dark w-100"><i class="bi bi-check2-circle"></i> ترحيل الرواتب (قيد تلقائي)</button>
      </form>
    <?php endif; ?>

    <?php if($run): ?>
      <div class="mt-2 text-secondary small">الحالة: <b><?= h($run['status']) ?></b></div>
    <?php endif; ?>
  </div>

  <div class="card cardx mt-3">
    <div class="p-3 d-flex align-items-center justify-content-between">
      <div class="fw-bold">تفاصيل الرواتب</div>
      <span class="text-secondary small"><?= count($lines) ?> موظف</span>
    </div>
    <div class="table-responsive px-3 pb-3">
      <table class="table align-middle mb-0">
        <thead>
          <tr class="text-secondary small">
            <th>الموظف</th>
            <th class="text-end">الراتب</th>
            <th class="text-end">خصم عهد</th>
            <th class="text-end">صافي</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($lines as $r): ?>
            <tr>
              <td class="fw-semibold"><?= h($r['full_name']) ?></td>
              <td class="text-end"><?= number_format((float)$r['base_salary'],2) ?></td>
              <td class="text-end"><?= number_format((float)$r['advances_deduction'],2) ?></td>
              <td class="text-end fw-semibold"><?= number_format((float)$r['net_salary'],2) ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if(!count($lines)): ?>
            <tr><td colspan="4" class="text-center text-secondary py-4">لم يتم توليد رواتب لهذا الشهر بعد</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php }); ?>
