<?php
// admin/daily_income.php

// --- 1. Debugging Enable ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once __DIR__ . "/includes/config.php";

// ✅ TIMEZONE FIX: PHP aur Database dono ko India ke time par set karna zaroori hai
date_default_timezone_set('Asia/Kolkata');
$conn->query("SET time_zone = '+05:30'"); 

// --- 2. Auth & DB Check ---
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}
if ($conn->connect_error) {
    die("Database Connection Failed: " . $conn->connect_error);
}

$error = $success = "";
$total_distributed = 0;
$distribution_log = [];

// --- 3. Check if Already Distributed Today ---
// ✅ CURDATE() ab exactly India ke raat 12 baje ke hisaab se kaam karega
$today_check_sql = "SELECT COUNT(*) FROM daily_income_log WHERE DATE(created_at) = CURDATE()";
$check_res = $conn->query($today_check_sql);
$already_distributed_count = $check_res ? (int)$check_res->fetch_row()[0] : 0;
$is_already_done = ($already_distributed_count > 0);

// 🟢 Distribute button click
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['distribute'])) {
    
    // Safety check again before processing
    if ($is_already_done) {
        $error = "⚠️ Income already distributed today! Action blocked to prevent double payment.";
    } else {
        $conn->begin_transaction();
        try {
            // Select active plans
            $stmt = $conn->prepare("
                SELECT up.user_id, up.daily_income, up.product_id, u.mobile 
                FROM user_purchases up 
                JOIN users u ON up.user_id = u.id 
                WHERE up.status = 'active'
            ");
            
            if (!$stmt) throw new Exception("Query Prep Failed: " . $conn->error);
            
            $stmt->execute();
            $res = $stmt->get_result();
            
            $count = 0;

            while ($row = $res->fetch_assoc()) {
                $uid = $row['user_id'];
                $income = (float)$row['daily_income'];
                $pid = (int)$row['product_id']; 
                $mobile = $row['mobile'];

                if ($income > 0) {
                    // Update User Balance
                    $stmt2 = $conn->prepare("UPDATE users SET income_balance = income_balance + ? WHERE id=?");
                    if(!$stmt2) throw new Exception("Update Prep Failed: " . $conn->error);
                    
                    $stmt2->bind_param("di", $income, $uid);
                    $stmt2->execute();
                    $stmt2->close();

                    // Insert Log
                    $stmt3 = $conn->prepare("INSERT INTO daily_income_log (user_id, product_id, amount, created_at) VALUES (?, ?, ?, NOW())");
                    if(!$stmt3) throw new Exception("Log Prep Failed: " . $conn->error);
                    
                    $stmt3->bind_param("iid", $uid, $pid, $income);
                    $stmt3->execute();
                    $stmt3->close();

                    $total_distributed += $income;
                    $distribution_log[] = [
                        'mobile' => $mobile,
                        'amount' => $income
                    ];
                    $count++;
                }
            }
            $stmt->close();

            if ($count > 0) {
                $conn->commit();
                $success = "✅ Income distributed successfully to $count plans! Total: ₹" . number_format($total_distributed, 2);
                $is_already_done = true; 
            } else {
                $conn->rollback();
                $error = "⚠️ No active plans found to distribute income.";
            }

        } catch (Exception $e) {
            $conn->rollback();
            $error = "❌ Failed to distribute income. Error: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Daily Income Distribution</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<style>
    :root {
        --bg: #091326; --card: #0f1c36; --accent: #00c6ff; --text: #e9f1ff; --success: #43a047; --danger: #e53935;
    }
    body {
        font-family: "Segoe UI", Arial, sans-serif;
        background: linear-gradient(180deg, #071022, #0a1430);
        margin: 0; padding: 0; color: var(--text);
        min-height: 100vh;
    }
    .header {
        background: #0c1730;
        padding: 15px; text-align: center; font-size: 20px; font-weight: bold;
        position: relative;
        border-bottom: 1px solid rgba(255,255,255,0.05);
        color: var(--accent);
    }
    .back-btn {
        position: absolute; left: 15px; top: 50%; transform: translateY(-50%);
        background: rgba(255,255,255,0.1); color: #fff; border: none; border-radius: 8px;
        width: 34px; height: 34px; cursor: pointer; font-weight: bold;
        display: flex; align-items: center; justify-content: center;
        text-decoration: none;
    }
    .container {
        max-width: 800px; margin: 30px auto; 
        background: var(--card); padding: 25px;
        border-radius: 16px; 
        box-shadow: 0 8px 32px rgba(0,0,0,0.3);
        border: 1px solid rgba(255,255,255,0.05);
    }
    .btn {
        padding: 16px 20px; border: none; border-radius: 12px;
        font-size: 16px; cursor: pointer; font-weight: 700; width: 100%;
        background: linear-gradient(90deg, #43a047, #00bcd4);
        color: #fff; margin-bottom: 20px; 
        box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        transition: .3s; 
    }
    .btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,0.4); }
    .btn:disabled, .btn.processing { 
        background: #333; cursor: not-allowed; transform: none; box-shadow: none; color: #888;
    }
    .alert {
        padding: 15px; border-radius: 10px; margin-bottom: 20px; font-weight: 600;
        display: flex; align-items: center; gap: 10px;
    }
    .alert.success { background: rgba(67, 160, 71, 0.2); color: #81c784; border: 1px solid rgba(67, 160, 71, 0.3); }
    .alert.error { background: rgba(229, 57, 53, 0.2); color: #e57373; border: 1px solid rgba(229, 57, 53, 0.3); }

    .total-box {
        background: linear-gradient(135deg, var(--card), #162440);
        padding: 20px; border-radius: 12px; margin-bottom: 25px;
        text-align: center; border: 1px solid rgba(255,255,255,0.08);
    }
    .total-box .label { color: var(--accent); font-size: 14px; text-transform: uppercase; letter-spacing: 1px; }
    .total-box .amount { font-size: 32px; font-weight: 800; margin-top: 5px; color: #fff; text-shadow: 0 0 20px rgba(0,198,255,0.3); }

    h2 { color: var(--accent); margin-top: 0; font-size: 18px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 10px; }
    .log-box {
        background: #091326; padding: 0; border-radius: 12px; max-height: 400px; overflow: auto;
        border: 1px solid rgba(255,255,255,0.05);
    }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 14px; text-align: left; font-size: 14px; border-bottom: 1px solid rgba(255,255,255,0.05); }
    th { background: #162440; color: var(--accent); position: sticky; top: 0; font-weight: 600; }
    td { color: #cfd8dc; }
    tr:last-child td { border-bottom: none; }
    .status-badge {
        display: inline-block; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; background: #1b5e20; color: #a5d6a7;
    }
</style>
</head>
<body>

<div class="header">
    <a href="dashboard.php" class="back-btn">←</a>
    💸 Daily Income Manager
</div>

<div class="container">
    <?php if($error): ?>
        <div class="alert error">❌ <?=$error?></div>
    <?php endif; ?>
    
    <?php if($success): ?>
        <div class="alert success">✅ <?=$success?></div>
    <?php endif; ?>

    <div class="total-box">
        <?php if ($is_already_done): ?>
            <div class="label">Status</div>
            <div class="amount" style="color:#81c784; font-size: 24px;">✅ Distributed for Today</div>
            <p style="color: #9aa7bf; margin: 5px 0 0;">Next distribution available tomorrow.</p>
        <?php else: ?>
            <div class="label">Ready to Distribute</div>
            <div class="amount">Waiting for Action...</div>
        <?php endif; ?>
    </div>

    <form method="post" id="distributeForm">
        <input type="hidden" name="distribute" value="1">
        <?php if ($is_already_done): ?>
            <button type="button" disabled class="btn">🚫 Income Already Distributed Today</button>
        <?php else: ?>
            <button type="button" id="submitBtn" class="btn" onclick="submitDistribution()">🚀 Click to Distribute Income</button>
        <?php endif; ?>
    </form>

    <?php if(!empty($distribution_log)): ?>
    <h2>📋 Just Distributed Log</h2>
    <div class="log-box">
        <table>
            <thead>
                <tr>
                    <th>User Mobile</th>
                    <th>Amount Added</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($distribution_log as $log): ?>
                <tr>
                    <td><?=$log['mobile']?></td>
                    <td>₹<?=number_format($log['amount'], 2)?></td>
                    <td><span class="status-badge">Success</span></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
        <?php 
            $recent_logs = [];
            if ($result = $conn->query("SELECT u.mobile, d.amount, d.created_at FROM daily_income_log d JOIN users u ON u.id=d.user_id ORDER BY d.id DESC LIMIT 5")) {
                while($row = $result->fetch_assoc()) $recent_logs[] = $row;
            }
        ?>
        <?php if(!empty($recent_logs)): ?>
        <h2>🕒 Recent Activity (Last 5)</h2>
        <div class="log-box">
            <table>
                <thead>
                    <tr>
                        <th>User Mobile</th>
                        <th>Amount</th>
                        <th>Time</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($recent_logs as $r): ?>
                    <tr>
                        <td><?=$r['mobile']?></td>
                        <td>₹<?=number_format($r['amount'], 2)?></td>
                        <td style="color:#9aa7bf;font-size:12px"><?=date('d M h:i A', strtotime($r['created_at']))?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<script>
// ✅ JAVASCRIPT FIX: Prevent Double Clicks
function submitDistribution() {
    if(confirm('Are you sure you want to distribute income to ALL active users? This cannot be undone.')) {
        var btn = document.getElementById('submitBtn');
        btn.innerHTML = '⏳ Processing... Please Wait';
        btn.classList.add('processing');
        btn.disabled = true; // Disable button immediately
        document.getElementById('distributeForm').submit();
    }
}
</script>

</body>
</html>