<?php
// admin/accounts/withdrawals.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit;
}

$account_filter = isset($_GET['account']) ? intval($_GET['account']) : 0;

// Get bank accounts for dropdown
$accounts = $pdo->query("SELECT id, account_name, account_number FROM bank_accounts WHERE status = 1 ORDER BY account_name")->fetchAll();

// Handle Add Withdrawal
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_withdrawal'])) {
    $account_id = intval($_POST['account_id'] ?? 0);
    $amount = floatval($_POST['amount'] ?? 0);
    $withdrawal_date = $_POST['withdrawal_date'] ?? date('Y-m-d');
    $payment_method = sanitize($_POST['payment_method'] ?? 'cash');
    $reference_no = sanitize($_POST['reference_no'] ?? '');
    $purpose = sanitize($_POST['purpose'] ?? '');
    $note = sanitize($_POST['note'] ?? '');

    if ($account_id > 0 && $amount > 0) {
        try {
            // Check if sufficient balance
            $stmt = $pdo->prepare("SELECT current_balance FROM bank_accounts WHERE id = ?");
            $stmt->execute([$account_id]);
            $balance = $stmt->fetch()['current_balance'] ?? 0;

            if ($amount > $balance) {
                $_SESSION['error_msg'] = 'Insufficient balance. Current balance: ' . number_format($balance) . ' TK';
            } else {
                $withdrawal_no = 'WTH-' . date('Ymd') . '-' . rand(1000, 9999);

                // Insert withdrawal
                $stmt = $pdo->prepare("INSERT INTO withdrawals 
                    (withdrawal_no, account_id, amount, withdrawal_date, payment_method, reference_no, purpose, note, created_by) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$withdrawal_no, $account_id, $amount, $withdrawal_date, $payment_method, $reference_no, $purpose, $note, $_SESSION['admin_id']]);

                // Update account balance
                $stmt = $pdo->prepare("UPDATE bank_accounts SET current_balance = current_balance - ? WHERE id = ?");
                $stmt->execute([$amount, $account_id]);

                // Add to transaction summary
                $stmt = $pdo->prepare("INSERT INTO account_transactions 
                    (account_id, transaction_type, reference_no, amount, transaction_date, description, created_by) 
                    VALUES (?, 'withdrawal', ?, ?, ?, ?, ?)");
                $stmt->execute([$account_id, $withdrawal_no, $amount, $withdrawal_date, $purpose ?: 'Withdrawal', $_SESSION['admin_id']]);

                $_SESSION['success_msg'] = 'Withdrawal added successfully!';
                header('Location: withdrawals.php');
                exit;
            }
        } catch (Exception $e) {
            $_SESSION['error_msg'] = 'Error: ' . $e->getMessage();
        }
    }
}

// Get withdrawals
$sql = "SELECT w.*, b.account_name, b.account_number 
        FROM withdrawals w 
        LEFT JOIN bank_accounts b ON w.account_id = b.id";
if ($account_filter > 0) {
    $sql .= " WHERE w.account_id = " . $account_filter;
}
$sql .= " ORDER BY w.created_at DESC";

$withdrawals = $pdo->query($sql)->fetchAll();

// Get total withdrawals
$total_withdrawals = 0;
foreach ($withdrawals as $wth) {
    $total_withdrawals += $wth['amount'];
}

include '../header.php';
?>

<style>
.withdrawal-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-box {
    background: #fff;
    border-radius: 12px;
    padding: 18px 20px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}

.stat-box .stat-number {
    font-size: 24px;
    font-weight: 700;
}

.stat-box .stat-label {
    font-size: 13px;
    color: #64748b;
}

.filter-group {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: center;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-arrow-up me-2"></i> Withdrawals</h2>
        <button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#withdrawalModal">
            <i class="fa-solid fa-plus"></i> Add Withdrawal
        </button>
    </div>

    <!-- Stats -->
    <div class="withdrawal-stats">
        <div class="stat-box">
            <div class="stat-number text-danger"><?php echo count($withdrawals); ?></div>
            <div class="stat-label">Total Withdrawals</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-danger"><?php echo number_format($total_withdrawals); ?> TK</div>
            <div class="stat-label">Total Amount</div>
        </div>
    </div>

    <?php if ($_SESSION['success_msg'] ?? ''): ?>
    <div class="alert alert-success"><?php echo $_SESSION['success_msg']; unset($_SESSION['success_msg']); ?></div>
    <?php endif; ?>
    <?php if ($_SESSION['error_msg'] ?? ''): ?>
    <div class="alert alert-danger"><?php echo $_SESSION['error_msg']; unset($_SESSION['error_msg']); ?></div>
    <?php endif; ?>

    <!-- Filter -->
    <div class="card p-3 mb-3">
        <form method="GET" class="filter-group">
            <div>
                <label class="form-label mb-0">Account</label>
                <select name="account" class="form-control" onchange="this.form.submit()">
                    <option value="0">All Accounts</option>
                    <?php foreach ($accounts as $acc): ?>
                    <option value="<?php echo $acc['id']; ?>" <?php echo $account_filter == $acc['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($acc['account_name']); ?> (<?php echo $acc['account_number']; ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="form-label mb-0">&nbsp;</label>
                <a href="withdrawals.php" class="btn btn-secondary">Clear</a>
            </div>
        </form>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Withdrawal No</th>
                            <th>Account</th>
                            <th>Amount</th>
                            <th>Method</th>
                            <th>Date</th>
                            <th>Purpose</th>
                            <th>Reference</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($withdrawals)): ?>
                        <tr><td colspan="8" class="text-center">No withdrawals found</td></tr>
                        <?php else: ?>
                        <?php foreach ($withdrawals as $wth): ?>
                        <tr>
                            <td><code><?php echo $wth['withdrawal_no']; ?></code></td>
                            <td><?php echo htmlspecialchars($wth['account_name'] ?? 'N/A'); ?></td>
                            <td class="text-danger fw-bold"><?php echo number_format($wth['amount']); ?> TK</td>
                            <td><?php echo ucfirst($wth['payment_method']); ?></td>
                            <td><?php echo date('d M Y', strtotime($wth['withdrawal_date'])); ?></td>
                            <td><?php echo htmlspecialchars($wth['purpose'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($wth['reference_no'] ?? '-'); ?></td>
                            <td>
                                <button onclick="deleteWithdrawal(<?php echo $wth['id']; ?>)" class="btn btn-sm btn-danger">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Withdrawal Modal -->
<div class="modal fade" id="withdrawalModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Withdrawal</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="add_withdrawal" value="1">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Bank Account *</label>
                        <select name="account_id" class="form-control" required>
                            <option value="">Select Account</option>
                            <?php foreach ($accounts as $acc): ?>
                            <option value="<?php echo $acc['id']; ?>">
                                <?php echo htmlspecialchars($acc['account_name']); ?> (<?php echo $acc['account_number']; ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Amount *</label>
                        <input type="number" name="amount" class="form-control" step="0.01" required>
                        <small class="text-muted">Current balance will be checked</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Withdrawal Date</label>
                        <input type="date" name="withdrawal_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Payment Method</label>
                        <select name="payment_method" class="form-control">
                            <option value="cash">Cash</option>
                            <option value="bank">Bank Transfer</option>
                            <option value="bkash">Bkash</option>
                            <option value="nagad">Nagad</option>
                            <option value="rocket">Rocket</option>
                            <option value="card">Card</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reference No</label>
                        <input type="text" name="reference_no" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Purpose</label>
                        <input type="text" name="purpose" class="form-control" placeholder="e.g. Office Rent, Salary, etc.">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Save Withdrawal</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function deleteWithdrawal(id) {
    if (confirm('Are you sure you want to delete this withdrawal?')) {
        window.location.href = 'delete-withdrawal.php?id=' + id;
    }
}
</script>

<?php include '../footer.php'; ?>