<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once __DIR__ . '/config.php';

// 1. Security: Login Required
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$userId = (int)$_SESSION['user_id'];

// 2. Fetch User Data
$stmtUser = $conn->prepare("SELECT id, username FROM users WHERE id = ?");
$stmtUser->bind_param("i", $userId);
$stmtUser->execute();
$user = $stmtUser->get_result()->fetch_assoc();

if (!$user) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// ==========================================
// 🛑 FILTER LOGIC (Deposit / Withdraw / All)
// ==========================================
$filterType = isset($_GET['type']) ? $_GET['type'] : 'all';
$history = [];

$pageTitle = 'Transaction History';
$headerIcon = 'fa-clock-rotate-left';

if ($filterType === 'deposit') {
    $pageTitle = 'Deposit History';
    $headerIcon = 'fa-wallet';
} elseif ($filterType === 'withdraw') {
    $pageTitle = 'Withdraw History';
    $headerIcon = 'fa-money-bill-transfer';
}

// 3. Fetch Data based on Filter
if ($filterType === 'all' || $filterType === 'transaction') {
    
    // A. Fetch Profit History (Eggs)
    $stmtProfit = $conn->prepare("SELECT id, 'Daily Profit' as type, amount as quantity, 0 as amount, 'Completed' as status, created_at, 'profit_history' as source FROM profit_history WHERE user_id = ?");
    $stmtProfit->bind_param("i", $userId);
    $stmtProfit->execute();
    $resProfit = $stmtProfit->get_result();
    while ($row = $resProfit->fetch_assoc()) {
        $history[] = $row;
    }

    // B. Fetch Transactions (Buy Hen / Sell Egg) with REJECT LOGIC
    // Hum LEFT JOIN use kar rahe hain taake check ho sake ke kya koi withdrawal reject hui hai
    $stmt1 = $conn->prepare("
        SELECT t.id, t.type, t.quantity, t.amount, t.created_at, 
               CASE 
                   WHEN t.type = 'Sell Egg' AND w.status = 'rejected' THEN 'Rejected'
                   ELSE t.status 
               END as status,
               t.type as source
        FROM transactions t
        LEFT JOIN withdrawals w ON t.user_id = w.user_id AND t.amount = w.amount AND t.created_at = w.created_at
        WHERE t.user_id = ?
    ");
    $stmt1->bind_param("i", $userId);
    $stmt1->execute();
    $res1 = $stmt1->get_result();
    while ($row = $res1->fetch_assoc()) {
        $history[] = $row;
    }
    
    // C. Fetch Investments (Pending/Rejected Hens)
    $stmt2 = $conn->prepare("SELECT id, item_type as type, quantity, total_amount as amount, status, created_at, 'investments' as source FROM investments WHERE user_id = ? AND status IN ('pending', 'rejected')");
    $stmt2->bind_param("i", $userId);
    $stmt2->execute();
    $res2 = $stmt2->get_result();
    while ($row = $res2->fetch_assoc()) {
        $row['type'] = 'Buy Hen (Pending)'; 
        $history[] = $row;
    }
}

if ($filterType === 'all' || $filterType === 'deposit') {
    // Deposits
    $stmt3 = $conn->prepare("SELECT id, 'Deposit' as type, 0 as quantity, amount, status, created_at, 'deposits' as source FROM deposits WHERE user_id = ?");
    $stmt3->bind_param("i", $userId);
    $stmt3->execute();
    $res3 = $stmt3->get_result();
    while ($row = $res3->fetch_assoc()) {
        $history[] = $row;
    }
}

if ($filterType === 'all' || $filterType === 'withdraw') {
    // Withdrawals
    $stmt4 = $conn->prepare("SELECT id, 'Withdraw' as type, 0 as quantity, amount, status, created_at, 'withdrawals' as source FROM withdrawals WHERE user_id = ?");
    $stmt4->bind_param("i", $userId);
    $stmt4->execute();
    $res4 = $stmt4->get_result();
    while ($row = $res4->fetch_assoc()) {
        $history[] = $row;
    }
}

// 4. Sort all history by Date Descending
usort($history, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

// Background Image
$bgURL = 'bg.png?v=' . (file_exists('bg.png') ? filemtime('bg.png') : time());
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?= $pageTitle ?> - MUQADAS POULTRY</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin:0; padding:0; box-sizing:border-box; font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        
        .fixed-bg {
            position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
            background-color: #0f172a;
            background-image: linear-gradient(rgba(15, 23, 42, 0.75), rgba(15, 23, 42, 0.85)), url('<?php echo $bgURL; ?>');
            background-size: cover; background-position: center; background-repeat: no-repeat; 
            z-index: -999; pointer-events: none;
        }

        body { color: #fff; display: flex; justify-content: center; min-height: 100vh; padding: 15px; }
        .container { width: 100%; max-width: 480px; display: flex; flex-direction: column; gap: 15px; }
        
        .header { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; }
        .back-btn { background: rgba(255,255,255,0.1); border:1px solid rgba(255,255,255,0.2); color:#fff; width:40px; height:40px; border-radius:50%; display:flex; align-items:center; justify-content:center; text-decoration:none; backdrop-filter:blur(5px); transition: 0.3s; }
        .back-btn:hover { background: rgba(255,255,255,0.25); transform: scale(1.05); }
        .brand-title { font-weight: 700; font-size: 1.2rem; color: #fff; text-shadow: 0 2px 4px rgba(0,0,0,0.8); }
        
        .card-box { background: rgba(15, 23, 42, 0.7); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 20px; padding: 20px; backdrop-filter: blur(12px); box-shadow: 0 8px 32px rgba(0,0,0,0.6); }
        .section-title { font-size: 1.1rem; color: #facc15; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; font-weight: 700; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 10px;}

        .tx-list { display: flex; flex-direction: column; gap: 12px; }
        
        .tx-item { 
            display: flex; align-items: center; justify-content: space-between;
            background: rgba(255, 255, 255, 0.03); 
            border: 1px solid rgba(255, 255, 255, 0.08);
            padding: 15px; border-radius: 14px; transition: 0.3s;
        }
        .tx-item:hover { background: rgba(255, 255, 255, 0.08); border-color: rgba(250, 204, 21, 0.3); }

        .tx-left { display: flex; align-items: center; gap: 14px; }
        
        .tx-icon { 
            width: 48px; height: 48px; border-radius: 12px; 
            display: flex; align-items: center; justify-content: center; 
            font-size: 1.3rem; flex-shrink: 0;
        }
        .icon-buy { background: rgba(59, 130, 246, 0.15); color: #60a5fa; border: 1px solid rgba(59, 130, 246, 0.3); }
        .icon-sell { background: rgba(34, 197, 94, 0.15); color: #4ade80; border: 1px solid rgba(34, 197, 94, 0.3); }
        .icon-rejected { background: rgba(239, 68, 68, 0.15); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
        .icon-deposit { background: rgba(168, 85, 247, 0.15); color: #c084fc; border: 1px solid rgba(168, 85, 247, 0.3); }
        .icon-withdraw { background: rgba(239, 68, 68, 0.15); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
        .icon-profit { background: rgba(250, 204, 21, 0.15); color: #facc15; border: 1px solid rgba(250, 204, 21, 0.3); }

        .tx-details h4 { font-size: 0.95rem; color: #f8fafc; font-weight: 600; margin-bottom: 4px; }
        .tx-details p { font-size: 0.75rem; color: #94a3b8; }

        .tx-right { text-align: right; }
        .tx-amount { font-size: 1.1rem; font-weight: 800; margin-bottom: 5px; }
        .tx-amount.plus { color: #4ade80; }
        .tx-amount.minus { color: #f87171; }
        .tx-amount.egg { color: #facc15; }
        
        .status-badge { 
            font-size: 0.65rem; font-weight: 700; padding: 4px 10px; border-radius: 6px; 
            text-transform: uppercase; letter-spacing: 0.5px;
            display: inline-block;
        }
        .st-completed { background: rgba(34, 197, 94, 0.2); color: #4ade80; border: 1px solid rgba(34,197,94,0.3); }
        .st-approved { background: rgba(34, 197, 94, 0.2); color: #4ade80; border: 1px solid rgba(34,197,94,0.3); }
        .st-pending { background: rgba(250, 204, 21, 0.2); color: #facc15; border: 1px solid rgba(250,204,21,0.3); }
        .st-rejected { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239,68,68,0.3); }
        .st-failed { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239,68,68,0.3); }

        .empty-state { text-align: center; padding: 50px 20px; color: #94a3b8; }
        .empty-state i { font-size: 3.5rem; color: rgba(255,255,255,0.1); margin-bottom: 15px; }
        .empty-state p { font-size: 0.95rem; line-height: 1.5; }
    </style>
</head>
<body>

<div class="fixed-bg"></div>

<div class="container">
    <div class="header">
        <a href="dashboard.php" class="back-btn"><i class="fa-solid fa-arrow-left"></i></a>
        <div class="brand-title"><?= $pageTitle ?></div>
        <div style="width:40px;"></div>
    </div>

    <div class="card-box">
        <div class="section-title"><i class="fa-solid <?= $headerIcon ?>"></i> <?= $pageTitle ?></div>
        
        <div class="tx-list">
            <?php if (empty($history)): ?>
                <div class="empty-state">
                    <i class="fa-solid fa-receipt"></i>
                    <p>No records found.<br>Your transaction history will appear here.</p>
                </div>
            <?php else: ?>
                <?php foreach ($history as $tx): 
                    $type = $tx['type'];
                    $status = strtolower($tx['status']);
                    $amount = (float)$tx['amount'];
                    $quantity = (int)$tx['quantity'];
                    
                    // Defaults
                    $iconClass = 'icon-buy';
                    $iconFa = 'fa-kiwi-bird';
                    $amountClass = 'minus';
                    $displayAmount = '- Rs ' . number_format($amount, 2);
                    
                    // 🛑 LOGIC: Reject Hone par icon aur color change karein
                    if ($status === 'rejected') {
                        $iconClass = 'icon-rejected'; 
                        $iconFa = 'fa-times-circle'; 
                        $amountClass = 'minus';
                        // Reject hone par amount red mein dikhayen
                        $displayAmount = '- Rs ' . number_format($amount, 2); 
                    } 
                    elseif ($type === 'Buy Hen' || $type === 'Buy Hen (Pending)') {
                        $iconClass = 'icon-buy'; 
                        $iconFa = 'fa-kiwi-bird'; 
                        $amountClass = 'minus'; 
                        $displayAmount = '- Rs ' . number_format($amount, 2);
                    
                    } elseif ($type === 'Sell Egg') {
                        $iconClass = 'icon-sell'; 
                        $iconFa = 'fa-egg'; 
                        $amountClass = 'plus'; 
                        $displayAmount = '+ Rs ' . number_format($amount, 2);
                    
                    } elseif ($type === 'Daily Profit') {
                        $iconClass = 'icon-profit'; 
                        $iconFa = 'fa-kiwi-bird'; 
                        $amountClass = 'egg'; 
                        $displayAmount = '+ ' . $quantity . ' ' . ($quantity > 1 ? 'Eggs' : 'Egg');
                    
                    } elseif ($type === 'Deposit') {
                        $iconClass = 'icon-deposit'; 
                        $iconFa = 'fa-wallet'; 
                        $amountClass = 'plus'; 
                        $displayAmount = '+ Rs ' . number_format($amount, 2);
                    
                    } elseif ($type === 'Withdraw') {
                        $iconClass = 'icon-withdraw'; 
                        $iconFa = 'fa-money-bill-transfer'; 
                        $amountClass = 'minus'; 
                        $displayAmount = '- Rs ' . number_format($amount, 2);
                    }

                    // Status Handling
                    if($status === '1') $status = 'approved';
                    if($status === '0') $status = 'pending';
                    $stClass = 'st-' . $status;
                ?>
                <div class="tx-item">
                    <div class="tx-left">
                        <div class="tx-icon <?= $iconClass ?>">
                            <i class="fa-solid <?= $iconFa ?>"></i>
                        </div>
                        <div class="tx-details">
                            <h4><?= htmlspecialchars($type) ?></h4>
                            <p><?= date('d M Y, h:i A', strtotime($tx['created_at'])) ?></p>
                        </div>
                    </div>
                    <div class="tx-right">
                        <div class="tx-amount <?= $amountClass ?>"><?= $displayAmount ?></div>
                        <div class="status-badge <?= $stClass ?>"><?= ucfirst($status) ?></div>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

</body>
</html>