<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/BranchBalance.php';
require_once __DIR__ . '/../classes/Withdrawal.php';

$branchId = $_SESSION['branch_id'] ?? 0;
if (!$branchId) {
    redirect('/login.php', 'Session tidak valid', 'error');
}

$pageTitle = 'Penarikan Saldo';

// Handle request withdrawal
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'request_withdrawal') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        $amount = (float) $_POST['amount'];
        $bankName = trim($_POST['bank_name']);
        $accountNumber = trim($_POST['account_number']);
        $accountHolder = trim($_POST['account_holder']);
        $notes = trim($_POST['notes'] ?? '');
        
        $result = Withdrawal::create(
            $branchId,
            $amount,
            $bankName,
            $accountNumber,
            $accountHolder,
            currentUserId(),
            $notes
        );
        
        if ($result['success']) {
            logActivity(currentUserId(), 'request_withdrawal', "Request penarikan Rp " . number_format($amount));
            redirect('/branch/withdrawal.php', '✅ Request penarikan berhasil diajukan');
        } else {
            redirect('/branch/withdrawal.php', '❌ ' . $result['error'], 'error');
        }
    }
}

$balance = BranchBalance::getBalance($branchId);
$withdrawals = Withdrawal::getByBranch($branchId);
$transactions = BranchBalance::getTransactions($branchId, 20);

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>
<div class="main-content">
  <h3><i class="bi bi-cash-stack me-2"></i>Penarikan Saldo</h3>
  
  <?= flashMessage() ?>
  
  <!-- Balance Cards -->
  <div class="row g-3 mb-4">
    <div class="col-md-4">
      <div class="card border-success">
        <div class="card-body text-center">
          <h6 class="text-muted mb-1">Saldo Tersedia</h6>
          <h2 class="text-success mb-0">Rp <?= number_format($balance['balance']) ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card border-primary">
        <div class="card-body text-center">
          <h6 class="text-muted mb-1">Total Pemasukan</h6>
          <h2 class="text-primary mb-0">Rp <?= number_format($balance['total_income']) ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card border-warning">
        <div class="card-body text-center">
          <h6 class="text-muted mb-1">Total Penarikan</h6>
          <h2 class="text-warning mb-0">Rp <?= number_format($balance['total_withdrawn']) ?></h2>
        </div>
      </div>
    </div>
  </div>
  
  <div class="row g-4">
    <!-- Request Form -->
    <div class="col-md-5">
      <div class="card">
        <div class="card-header bg-primary text-white">
          <i class="bi bi-plus-circle me-2"></i>Request Penarikan
        </div>
        <div class="card-body">
          <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="request_withdrawal">
            
            <div class="mb-3">
              <label class="form-label">Jumlah Penarikan *</label>
              <div class="input-group">
                <span class="input-group-text">Rp</span>
                <input type="number" name="amount" class="form-control" 
                       min="50000" max="<?= $balance['balance'] ?>" step="1000" required>
              </div>
              <small class="text-muted">Minimum Rp 50.000 | Maksimum: Rp <?= number_format($balance['balance']) ?></small>
            </div>
            
            <div class="mb-3">
              <label class="form-label">Nama Bank *</label>
              <select name="bank_name" class="form-select" required>
                <option value="">-- Pilih Bank --</option>
                <option value="BCA">BCA</option>
                <option value="Mandiri">Mandiri</option>
                <option value="BNI">BNI</option>
                <option value="BRI">BRI</option>
                <option value="BSI">BSI</option>
                <option value="CIMB">CIMB Niaga</option>
              </select>
            </div>
            
            <div class="mb-3">
              <label class="form-label">Nomor Rekening *</label>
              <input type="text" name="account_number" class="form-control" required>
            </div>
            
            <div class="mb-3">
              <label class="form-label">Nama Pemilik Rekening *</label>
              <input type="text" name="account_holder" class="form-control" required>
            </div>
            
            <div class="mb-3">
              <label class="form-label">Catatan (Opsional)</label>
              <textarea name="notes" class="form-control" rows="2"></textarea>
            </div>
            
            <button type="submit" class="btn btn-primary w-100">
              <i class="bi bi-send"></i> Ajukan Request
            </button>
          </form>
        </div>
      </div>
    </div>
    
    <!-- Withdrawal History -->
    <div class="col-md-7">
      <div class="card">
        <div class="card-header">
          <i class="bi bi-clock-history me-2"></i>Riwayat Penarikan
        </div>
        <div class="card-body p-0">
          <?php if (empty($withdrawals)): ?>
            <div class="text-center py-4 text-muted">
              <i class="bi bi-inbox fs-1"></i>
              <p class="mt-2">Belum ada request penarikan</p>
            </div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-hover mb-0">
                <thead class="table-light">
                  <tr>
                    <th>Tanggal</th>
                    <th>Jumlah</th>
                    <th>Rekening</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($withdrawals as $w): ?>
                    <tr>
                      <td>
                        <small><?= date('d/m/Y H:i', strtotime($w['requested_at'])) ?></small>
                      </td>
                      <td>
                        <strong>Rp <?= number_format($w['amount']) ?></strong>
                      </td>
                      <td>
                        <small>
                          <?= htmlspecialchars($w['bank_name']) ?><br>
                          <?= htmlspecialchars($w['account_number']) ?><br>
                          <?= htmlspecialchars($w['account_holder']) ?>
                        </small>
                      </td>
                      <td>
                        <?php if ($w['status'] === 'pending'): ?>
                          <span class="badge bg-warning text-dark">
                            <i class="bi bi-clock"></i> Pending
                          </span>
                        <?php elseif ($w['status'] === 'approved'): ?>
                          <span class="badge bg-success">
                            <i class="bi bi-check-circle"></i> Approved
                          </span>
                          <?php if (!empty($w['processed_at'])): ?>
                            <br><small class="text-muted"><?= date('d/m/Y H:i', strtotime($w['processed_at'])) ?></small>
                          <?php endif; ?>
                        <?php elseif ($w['status'] === 'rejected'): ?>
                          <span class="badge bg-danger" title="<?= htmlspecialchars($w['rejection_reason'] ?? '') ?>">
                            <i class="bi bi-x-circle"></i> Rejected
                          </span>
                        <?php endif; ?>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>
      </div>
      
      <!-- Recent Transactions -->
      <div class="card mt-3">
        <div class="card-header">
          <i class="bi bi-receipt me-2"></i>Transaksi Terakhir
        </div>
        <div class="card-body p-0">
          <?php if (empty($transactions)): ?>
            <div class="text-center py-4 text-muted">
              <i class="bi bi-inbox fs-1"></i>
              <p class="mt-2">Belum ada transaksi</p>
            </div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-sm mb-0">
                <thead class="table-light">
                  <tr>
                    <th>Tanggal</th>
                    <th>Tipe</th>
                    <th>Jumlah</th>
                    <th>Keterangan</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($transactions as $t): ?>
                    <tr>
                      <td><small><?= date('d/m/Y H:i', strtotime($t['created_at'])) ?></small></td>
                      <td>
                        <?php if ($t['type'] === 'income'): ?>
                          <span class="badge bg-success">Masuk</span>
                        <?php elseif ($t['type'] === 'withdrawal'): ?>
                          <span class="badge bg-warning">Keluar</span>
                        <?php else: ?>
                          <span class="badge bg-info">Adjustment</span>
                        <?php endif; ?>
                      </td>
                      <td>
                        <strong class="<?= $t['type'] === 'income' ? 'text-success' : 'text-danger' ?>">
                          <?= $t['type'] === 'income' ? '+' : '-' ?> Rp <?= number_format($t['amount']) ?>
                        </strong>
                      </td>
                      <td><small><?= htmlspecialchars($t['description'] ?? '-') ?></small></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>
<?php require __DIR__ . '/../includes/footer.php'; ?>