<?php
/**
 * credit_daily_profits.php
 *
 * TWO PLAN TYPES:
 * ─────────────────────────────────────────────────────────────────────────────
 * FIXED  ("Profit Only")
 *   • Capital stays locked until maturity — user NEVER gets capital back.
 *   • Daily profit = (capital × roi_percentage / 100) / duration_days
 *   • Each day's profit is credited to users.balance immediately (withdrawable).
 *   • On maturity: investment marked 'matured'. Capital is NOT returned.
 *
 * FLEXIBLE  ("Profit + Capital")
 *   • A short-term plan (e.g. 1 day).
 *   • On maturity day: credit (profit + capital) as a lump sum to users.balance.
 *   • No daily drip — everything comes at once on maturity.
 * ─────────────────────────────────────────────────────────────────────────────
 *
 * Usage:  require_once 'credit_daily_profits.php';
 *         creditDailyProfits($conn, $user_id);
 */

function creditDailyProfits(mysqli $conn, int $user_id): void
{
    // ── Ensure tracking table exists ─────────────────────────────────────────
    mysqli_query($conn, "
        CREATE TABLE IF NOT EXISTS `daily_profit_credits` (
            `id`            int(11)        NOT NULL AUTO_INCREMENT,
            `investment_id` int(11)        NOT NULL,
            `user_id`       int(11)        NOT NULL,
            `amount`        decimal(10,2)  NOT NULL,
            `credit_date`   date           NOT NULL,
            `type`          enum('daily_profit','capital_return','flexible_maturity') NOT NULL DEFAULT 'daily_profit',
            `created_at`    timestamp      NULL DEFAULT current_timestamp(),
            PRIMARY KEY (`id`),
            UNIQUE KEY `unique_daily` (`investment_id`, `credit_date`, `type`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $today    = date('Y-m-d');
    $today_ts = strtotime($today);

    // ── Fetch all active investments for this user ────────────────────────────
    $sql = "
        SELECT  i.id,
                i.user_id,
                i.amount,
                i.return_type,
                i.profit         AS total_profit_promised,
                DATE(i.start_date)    AS start_date,
                DATE(i.maturity_date) AS maturity_date,
                COALESCE(p.roi_percentage, 0)  AS roi_pct,
                COALESCE(p.duration_days,  90) AS duration_days
        FROM investments i
        LEFT JOIN investment_plans p ON i.plan_id = p.id
        WHERE i.user_id = $user_id
          AND i.status IN ('running','active','')
          AND i.paused  = 0
    ";

    $result = mysqli_query($conn, $sql);
    if (!$result) return;

    while ($inv = mysqli_fetch_assoc($result)) {

        $inv_id      = (int)$inv['id'];
        $amount      = (float)$inv['amount'];
        $roi_pct     = (float)$inv['roi_pct'];
        $duration    = max(1, (int)$inv['duration_days']);
        $return_type = $inv['return_type']; // 'fixed' | 'flexible'

        $start_ts    = strtotime($inv['start_date']);
        $maturity_ts = strtotime($inv['maturity_date']);

        if ($amount <= 0) continue;

        // ════════════════════════════════════════════════════════════════════
        // FIXED plan — daily profit drip, capital NEVER returned
        // ════════════════════════════════════════════════════════════════════
        if ($return_type === 'fixed') {

            if ($roi_pct <= 0) continue;

            // Daily slice = total ROI / number of days
            $daily_profit = round(($amount * $roi_pct / 100) / $duration, 2);
            if ($daily_profit <= 0) continue;

            // Credit every uncredited day from day-after-start up to today (capped at maturity)
            $credit_until = min($today_ts, $maturity_ts);
            $cursor       = $start_ts + 86400; // Day 1

            while ($cursor <= $credit_until) {
                $credit_date = date('Y-m-d', $cursor);

                $check = mysqli_query($conn,
                    "SELECT id FROM daily_profit_credits
                     WHERE investment_id = $inv_id
                       AND credit_date   = '$credit_date'
                       AND type          = 'daily_profit'
                     LIMIT 1"
                );

                if (mysqli_num_rows($check) === 0) {
                    $ins = mysqli_query($conn,
                        "INSERT IGNORE INTO daily_profit_credits
                             (investment_id, user_id, amount, credit_date, type)
                         VALUES ($inv_id, $user_id, $daily_profit, '$credit_date', 'daily_profit')"
                    );

                    if ($ins && mysqli_affected_rows($conn) > 0) {
                        mysqli_query($conn,
                            "INSERT INTO profits (user_id, amount, source)
                             VALUES ($user_id, $daily_profit,
                                     'Daily Profit - Investment #$inv_id ($credit_date)')"
                        );
                        mysqli_query($conn,
                            "UPDATE users SET balance = balance + $daily_profit
                             WHERE id = $user_id"
                        );
                    }
                }

                $cursor += 86400;
            }

            // Mark matured when time is up (capital is NOT returned for fixed)
            if ($today_ts >= $maturity_ts) {
                mysqli_query($conn,
                    "UPDATE investments SET status = 'matured'
                     WHERE id = $inv_id AND status IN ('running','active','')"
                );
            }
        }

        // ════════════════════════════════════════════════════════════════════
        // FLEXIBLE plan — lump sum (profit + capital) credited on maturity day
        // ════════════════════════════════════════════════════════════════════
        elseif ($return_type === 'flexible') {

            if ($today_ts < $maturity_ts) continue; // Not mature yet

            // Check if maturity payout has already been done
            $cap_check = mysqli_query($conn,
                "SELECT id FROM daily_profit_credits
                 WHERE investment_id = $inv_id
                   AND type IN ('flexible_maturity','capital_return')
                 LIMIT 1"
            );

            if (mysqli_num_rows($cap_check) === 0) {
                // Total payout = capital + profit
                $total_profit  = round(($amount * $roi_pct) / 100, 2);
                $total_payout  = round($amount + $total_profit, 2);
                $maturity_date = date('Y-m-d', $maturity_ts);

                $ins = mysqli_query($conn,
                    "INSERT IGNORE INTO daily_profit_credits
                         (investment_id, user_id, amount, credit_date, type)
                     VALUES ($inv_id, $user_id, $total_payout, '$maturity_date', 'flexible_maturity')"
                );

                if ($ins && mysqli_affected_rows($conn) > 0) {
                    // Record in profits table
                    mysqli_query($conn,
                        "INSERT INTO profits (user_id, amount, source)
                         VALUES ($user_id, $total_payout,
                                 'Maturity Payout - Investment #$inv_id (Capital + Profit)')"
                    );
                    // Credit to balance
                    mysqli_query($conn,
                        "UPDATE users SET balance = balance + $total_payout
                         WHERE id = $user_id"
                    );
                }
            }

            // Mark matured
            mysqli_query($conn,
                "UPDATE investments SET status = 'matured'
                 WHERE id = $inv_id AND status IN ('running','active','')"
            );
        }
    }
}