<?php
session_save_path(__DIR__ . '/../tmp');
if (!is_dir(__DIR__ . '/../tmp')) mkdir(__DIR__ . '/../tmp', 0777, true);
session_start();

if (!isset($_SESSION['user_id'])) {
  header("Location: /wood-system/login.php");
  exit;
}

require __DIR__ . '/../includes/db.php';
require __DIR__ . '/../includes/header.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// ====================================================
// ✅ عند الضغط على زر تصدير Excel
// ====================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['export_excel'])) {
  if (ob_get_length()) ob_end_clean();
  require __DIR__ . '/../vendor/autoload.php';

  $agent_id = (int)$_POST['agent_id'];

  // جلب اسم المخلص
  $stmt = $pdo->prepare("SELECT name FROM agents WHERE id=?");
  $stmt->execute([$agent_id]);
  $agent_name = $stmt->fetchColumn() ?: 'مخلص غير معروف';

  // --- جلب الحركات ---
  $movements = [];

  // قبض من المخلص
  $q1 = $pdo->prepare("
    SELECT am.date,
           CONCAT('قبض من المخلص: ', COALESCE(am.note,'')) AS descp,
           0 AS debit,
           am.amount AS credit
    FROM agent_money am
    WHERE am.agent_id = ? AND am.type = 'in'
  ");
  $q1->execute([$agent_id]);
  foreach ($q1 as $r) $movements[] = $r;

  // دفع للمخلص
  $q2 = $pdo->prepare("
    SELECT am.date,
           CONCAT('دفع للمخلص: ', COALESCE(am.note,'')) AS descp,
           am.amount AS debit,
           0 AS credit
    FROM agent_money am
    WHERE am.agent_id = ? AND am.type = 'out'
  ");
  $q2->execute([$agent_id]);
  foreach ($q2 as $r) $movements[] = $r;

  usort($movements, fn($a,$b)=>strcmp($a['date'],$b['date']));

  // --- إنشاء ملف Excel ---
  $spreadsheet = new Spreadsheet();
  $sheet = $spreadsheet->getActiveSheet();
  $sheet->setTitle('كشف حساب المخلص');

  // العنوان الرئيسي
  $sheet->setCellValue('A1', '📘 كشف حساب المخلص: ' . $agent_name);
  $sheet->mergeCells('A1:E1');
  $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);

  // رؤوس الأعمدة
  $headers = ['التاريخ','البيان','مدين','دائن','الرصيد'];
  $sheet->fromArray($headers, NULL, 'A3');
  $sheet->getStyle('A3:E3')->getFont()->setBold(true);

  // تعبئة البيانات
  $row = 4; $run = 0;
  foreach ($movements as $m) {
    $run += $m['debit'] - $m['credit'];
    $sheet->setCellValue('A'.$row, $m['date']);
    $sheet->setCellValue('B'.$row, $m['descp']);
    $sheet->setCellValue('C'.$row, $m['debit']);
    $sheet->setCellValue('D'.$row, $m['credit']);
    $sheet->setCellValue('E'.$row, $run);
    $row++;
  }

  // الإجماليات
  $sheet->setCellValue('A'.$row, 'الإجمالي');
  $sheet->setCellValue('C'.$row, '=SUM(C4:C'.($row-1).')');
  $sheet->setCellValue('D'.$row, '=SUM(D4:D'.($row-1).')');
  $sheet->setCellValue('E'.$row, '=C'.$row.'-D'.$row);
  $sheet->getStyle('A'.$row.':E'.$row)->getFont()->setBold(true);

  // ضبط الأعمدة
  foreach (range('A','E') as $col)
    $sheet->getColumnDimension($col)->setAutoSize(true);

  // تحميل الملف
  header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  header('Content-Disposition: attachment; filename="كشف حساب - '.$agent_name.'.xlsx"');
  header('Cache-Control: max-age=0');
  header('Pragma: public');

  $writer = new Xlsx($spreadsheet);
  $writer->save('php://output');
  exit;
}

// ====================================================
// ✅ عرض الصفحة العادية
// ====================================================
$agents = $pdo->query("SELECT id, name FROM agents ORDER BY name ASC")->fetchAll();
$agent_id = (int)($_GET['agent_id'] ?? 0);
$movements = [];

if ($agent_id) {
  $q1 = $pdo->prepare("
    SELECT am.date,
           CONCAT('قبض من المخلص: ', COALESCE(am.note,'')) AS descp,
           0 AS debit,
           am.amount AS credit
    FROM agent_money am
    WHERE am.agent_id = ? AND am.type = 'in'
  ");
  $q1->execute([$agent_id]);
  foreach ($q1 as $r) $movements[] = $r;

  $q2 = $pdo->prepare("
    SELECT am.date,
           CONCAT('دفع للمخلص: ', COALESCE(am.note,'')) AS descp,
           am.amount AS debit,
           0 AS credit
    FROM agent_money am
    WHERE am.agent_id = ? AND am.type = 'out'
  ");
  $q2->execute([$agent_id]);
  foreach ($q2 as $r) $movements[] = $r;

  usort($movements, fn($a,$b)=>strcmp($a['date'],$b['date']));
}
?>

<h3 class="mb-3">📘 كشف حساب المخلص</h3>

<form class="row g-3 mb-3">
  <div class="col-md-6">
    <label class="form-label">اختر المخلص</label>
    <select name="agent_id" class="form-select" onchange="this.form.submit()">
      <option value="">— اختر —</option>
      <?php foreach($agents as $a): ?>
        <option value="<?= $a['id'] ?>" <?= $agent_id == $a['id'] ? 'selected' : '' ?>>
          <?= htmlspecialchars($a['name']) ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>
</form>

<?php if ($agent_id): ?>
<form method="post" action="">
  <input type="hidden" name="export_excel" value="1">
  <input type="hidden" name="agent_id" value="<?= $agent_id ?>">
  <button class="btn btn-success mb-3">📤 تصدير إلى Excel</button>
</form>

<div class="card shadow-sm">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped mb-0 text-center align-middle">
        <thead class="table-dark">
          <tr>
            <th>التاريخ</th>
            <th>البيان</th>
            <th>مدين</th>
            <th>دائن</th>
            <th>الرصيد</th>
          </tr>
        </thead>
        <tbody>
          <?php 
          $running = 0; $total_debit = 0; $total_credit = 0;
          foreach ($movements as $m):
            $running += ($m['debit'] - $m['credit']);
            $total_debit += $m['debit'];
            $total_credit += $m['credit'];
          ?>
          <tr>
            <td><?= htmlspecialchars($m['date']) ?></td>
            <td><?= htmlspecialchars($m['descp']) ?></td>
            <td><?= $m['debit'] ? number_format($m['debit'], 2) : '-' ?></td>
            <td><?= $m['credit'] ? number_format($m['credit'], 2) : '-' ?></td>
            <td><strong><?= number_format($running, 2) ?></strong></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
        <tfoot>
          <tr class="table-light fw-bold">
            <th colspan="2">الإجمالي</th>
            <th><?= number_format($total_debit, 2) ?></th>
            <th><?= number_format($total_credit, 2) ?></th>
            <th><?= number_format($total_debit - $total_credit, 2) ?></th>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</div>
<?php endif; ?>

<?php require __DIR__ . '/../includes/footer.php'; ?>
