<?php
session_start();
require_once '../config/database.php';

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

$message = '';
$message_type = '';

// Handle reset action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_transactions'])) {
    try {
        $reset_type = $_POST['reset_type'] ?? '';
        $confirmation = $_POST['confirmation'] ?? '';
        
        // Validate confirmation
        if ($confirmation !== 'RESET_ALL_TRANSACTIONS') {
            throw new Exception("Please enter the exact confirmation text: RESET_ALL_TRANSACTIONS");
        }
        
        if (empty($reset_type)) {
            throw new Exception("Please select a reset type");
        }
        
        $pdo->beginTransaction();
        
        switch ($reset_type) {
            case 'pending_only':
                // Reset only pending transactions
                $stmt = $pdo->prepare("DELETE FROM bank_transactions WHERE status = 'pending'");
                $deleted_count = $stmt->rowCount();
                $stmt->execute();
                $message = "Successfully deleted {$deleted_count} pending transactions.";
                break;
                
            case 'verified_only':
                // Reset only verified transactions
                $stmt = $pdo->prepare("DELETE FROM bank_transactions WHERE status = 'verified'");
                $stmt->execute();
                $deleted_count = $stmt->rowCount();
                $message = "Successfully deleted {$deleted_count} verified transactions.";
                break;
                
            case 'rejected_only':
                // Reset only rejected transactions
                $stmt = $pdo->prepare("DELETE FROM bank_transactions WHERE status = 'rejected'");
                $stmt->execute();
                $deleted_count = $stmt->rowCount();
                $message = "Successfully deleted {$deleted_count} rejected transactions.";
                break;
                
            case 'all_except_verified':
                // Reset pending and rejected, keep verified
                $stmt1 = $pdo->prepare("DELETE FROM bank_transactions WHERE status = 'pending'");
                $stmt1->execute();
                $pending_count = $stmt1->rowCount();
                
                $stmt2 = $pdo->prepare("DELETE FROM bank_transactions WHERE status = 'rejected'");
                $stmt2->execute();
                $rejected_count = $stmt2->rowCount();
                
                $message = "Successfully deleted {$pending_count} pending and {$rejected_count} rejected transactions. Verified transactions preserved.";
                break;
                
            case 'everything':
                // Reset everything - complete wipe
                $stmt = $pdo->prepare("DELETE FROM bank_transactions");
                $stmt->execute();
                $deleted_count = $stmt->rowCount();
                $message = "Successfully deleted all {$deleted_count} bank transactions.";
                break;
                
            default:
                throw new Exception("Invalid reset type selected");
        }
        
        $pdo->commit();
        $message_type = 'success';
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Get transaction statistics
$stats = [];
try {
    $stmt = $pdo->query("SELECT 
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count,
        SUM(CASE WHEN status = 'verified' THEN 1 ELSE 0 END) as verified_count,
        SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected_count,
        COUNT(*) as total_count,
        SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) as pending_amount,
        SUM(CASE WHEN status = 'verified' THEN amount ELSE 0 END) as verified_amount,
        SUM(CASE WHEN status = 'rejected' THEN amount ELSE 0 END) as rejected_amount
        FROM bank_transactions");
    $stats = $stmt->fetch();
} catch (Exception $e) {
    $stats = [
        'pending_count' => 0,
        'verified_count' => 0,
        'rejected_count' => 0,
        'total_count' => 0,
        'pending_amount' => 0,
        'verified_amount' => 0,
        'rejected_amount' => 0
    ];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Bank Transactions - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .admin-header {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }
        .card {
            border-radius: 10px;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        .stat-card {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
        }
        .stat-card.pending {
            background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
        }
        .stat-card.verified {
            background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
        }
        .stat-card.rejected {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
        }
        .warning-box {
            border-left: 4px solid #dc3545;
            background-color: #f8d7da;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="admin-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1><i class="fas fa-trash-alt"></i> Reset Bank Transactions</h1>
                    <p class="mb-0">Admin tool to reset/clear bank transaction data</p>
                </div>
                <div class="col-md-4 text-end">
                    <a href="index.php" class="btn btn-light">
                        <i class="fas fa-arrow-left"></i> Back to Dashboard
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Statistics Cards -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <h3><?php echo $stats['total_count']; ?></h3>
                        <p class="mb-0">Total Transactions</p>
                        <h4>৳<?php echo number_format($stats['pending_amount'] + $stats['verified_amount'] + $stats['rejected_amount'], 2); ?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card stat-card pending">
                    <div class="card-body text-center">
                        <h3><?php echo $stats['pending_count']; ?></h3>
                        <p class="mb-0">Pending</p>
                        <h4>৳<?php echo number_format($stats['pending_amount'], 2); ?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card stat-card verified">
                    <div class="card-body text-center">
                        <h3><?php echo $stats['verified_count']; ?></h3>
                        <p class="mb-0">Verified</p>
                        <h4>৳<?php echo number_format($stats['verified_amount'], 2); ?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card stat-card rejected">
                    <div class="card-body text-center">
                        <h3><?php echo $stats['rejected_count']; ?></h3>
                        <p class="mb-0">Rejected</p>
                        <h4>৳<?php echo number_format($stats['rejected_amount'], 2); ?></h4>
                    </div>
                </div>
            </div>
        </div>

        <!-- Reset Form -->
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card">
                    <div class="card-header bg-danger text-white">
                        <h4 class="mb-0"><i class="fas fa-exclamation-triangle"></i> Reset Bank Transactions</h4>
                    </div>
                    <div class="card-body">
                        <div class="warning-box p-3 mb-4">
                            <h5><i class="fas fa-exclamation-circle"></i> Warning!</h5>
                            <p class="mb-0">This action cannot be undone. Please be very careful when resetting bank transactions. Make sure you have backups if needed.</p>
                        </div>

                        <form method="POST" onsubmit="return confirmReset()">
                            <div class="mb-3">
                                <label class="form-label">Reset Type</label>
                                <select class="form-select" name="reset_type" required>
                                    <option value="">Select reset option...</option>
                                    <option value="pending_only">Delete Pending Transactions Only</option>
                                    <option value="verified_only">Delete Verified Transactions Only</option>
                                    <option value="rejected_only">Delete Rejected Transactions Only</option>
                                    <option value="all_except_verified">Delete All Except Verified</option>
                                    <option value="everything">Delete Everything (Complete Reset)</option>
                                </select>
                                <div class="form-text">Choose what type of transactions to reset</div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Confirmation</label>
                                <input type="text" class="form-control" name="confirmation" placeholder="Type: RESET_ALL_TRANSACTIONS" required>
                                <div class="form-text">Type exactly: <strong>RESET_ALL_TRANSACTIONS</strong> to confirm</div>
                            </div>

                            <div class="d-grid gap-2">
                                <button type="submit" name="reset_transactions" class="btn btn-danger btn-lg">
                                    <i class="fas fa-trash-alt"></i> Reset Bank Transactions
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function confirmReset() {
            const resetType = document.querySelector('select[name="reset_type"]').value;
            const confirmation = document.querySelector('input[name="confirmation"]').value;
            
            if (confirmation !== 'RESET_ALL_TRANSACTIONS') {
                alert('Please enter the exact confirmation text: RESET_ALL_TRANSACTIONS');
                return false;
            }
            
            let message = 'Are you sure you want to ';
            switch(resetType) {
                case 'pending_only':
                    message += 'delete all pending transactions?';
                    break;
                case 'verified_only':
                    message += 'delete all verified transactions? This cannot be recovered!';
                    break;
                case 'rejected_only':
                    message += 'delete all rejected transactions?';
                    break;
                case 'all_except_verified':
                    message += 'delete all pending and rejected transactions? Verified transactions will be kept.';
                    break;
                case 'everything':
                    message += 'delete ALL bank transactions? This cannot be undone!';
                    break;
                default:
                    alert('Please select a reset type');
                    return false;
            }
            
            return confirm(message + '\n\nThis action cannot be undone!');
        }
    </script>
</body>
</html>