<?php 
require_once("header.php");

// Fetch settings
$stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC LIMIT 1");
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row) {
    $cphone = $row['phone'] ?? '';
    $curl = $row['url'] ?? '';
    $cdomain = $row['domain'] ?? '';
    $cname = $row['domain_name'] ?? '';
    $cpass = $row['password'] ?? '';
    $cemail = $row['email2'] ?? '';
    $cright = $row['copyright'] ?? '';
    $chost = $row['contact_email'] ?? '';
    $cport = $row['service1'] ?? '';
}

// Include PHPMailer
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Confirm deposit action
if (isset($_POST['action'])) {
    $log_id    = (int)$_POST['log_id'];
    $email     = htmlspecialchars($_POST['email']);
    $amount    = (float)$_POST['amount'];
    $amt       = (float)$_POST['amt'];
    $signa     = htmlspecialchars($_POST['signa']);
    $user_rate2= (float)$_POST['user_rate2'];
    $user_cur2 = htmlspecialchars($_POST['user_cur2']);

    // Safe division
    // if (!empty($user_rate2) && $user_rate2 > 0) {
    //     $ammt = $amt / $user_rate2;
    // } else {
    //     $ammt = 0;
    //     echo "<div class='alert alert-danger'>❌ Currency rate missing or invalid. Deposit not processed.</div>";
    // }

    try {
        // Update user balance
        $stmt = $pdo->prepare("UPDATE logins 
            SET balance = balance + :ammt, 
                ibalance = ibalance + :ammt, 
                cdeposit = cdeposit + 1, 
                confirm = 0, 
                signa = :signa 
            WHERE id = :log_id");
        $stmt->execute([
            ':ammt' => $amt,
            ':signa' => $signa,
            ':log_id' => $log_id
        ]);

        // Update deposit table
        $id = (int)$_GET['id'];
        $stmt = $pdo->prepare("UPDATE deposit SET status = 2 WHERE id = :id");
        $stmt->execute(['id' => $id]);

        // --- Referral Bonus (5%) ---
        $bonus = $amt * 0.05;

        // Get the user to find their referrer
        $userStmt = $pdo->prepare("SELECT id, refid FROM logins WHERE id = :id");
        $userStmt->execute(['id' => $log_id]);
        $user = $userStmt->fetch(PDO::FETCH_ASSOC);

        if ($user && !empty($user['refid'])) {
            $refid = (int)$user['refid'];

            // Update referrer stats in logins
            $pdo->prepare("UPDATE logins 
                SET refcom = refcom + :bonus, 
                    reftot = reftot + 1, 
                    refact = refact + 1 
                WHERE id = :refid")
                ->execute(['bonus' => $bonus, 'refid' => $refid]);

            // Insert into ref table
            $refUserStmt = $pdo->prepare("SELECT username, phone, email FROM logins WHERE id = :id");
            $refUserStmt->execute(['id' => $refid]);
            $refUser = $refUserStmt->fetch(PDO::FETCH_ASSOC);

            if ($refUser) {
                $pdo->prepare("INSERT INTO ref (userid, username, phone, email, amount, date) 
                    VALUES (:userid, :username, :phone, :email, :amount, NOW())")
                    ->execute([
                        'userid' => $refid,
                        'username' => $refUser['username'],
                        'phone' => $refUser['phone'],
                        'email' => $refUser['email'],
                        'amount' => $bonus
                    ]);
            }
        }

        $success = "<div class='alert alert-success'>✅ Deposit confirmed successfully. <meta http-equiv='refresh' content='3; url=adminverify.php'></div>";

    } catch (PDOException $e) {
        echo "<div class='alert alert-danger'>❌ Error: " . $e->getMessage() . "</div>";
    }
}

// Fetch deposit row
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$stmt = $pdo->prepare("SELECT * FROM deposit WHERE id = :id");
$stmt->execute(['id' => $id]);
$ordrow = $stmt->fetch(PDO::FETCH_ASSOC);

?>

<hr>

<?php if (isset($success)) echo $success; ?>

<?php if ($ordrow): ?>
<div class="main-panel">
  <div class="content bg-light">
    <div class="page-inner">
      <div class="table-responsive">
        <form action="" method="post" class="reservation-form mb-0 bg-silver-deep p-30">
          <input type="hidden" name="log_id" value="<?= htmlspecialchars($ordrow['log_id']) ?>">
          <input type="hidden" name="email" value="<?= htmlspecialchars($ordrow['email']) ?>">
          <input type="hidden" name="user_cur2" value="<?= htmlspecialchars($ordrow['user_cur']) ?>">
          <input type="hidden" name="user_rate2" value="<?= htmlspecialchars($ordrow['cur_rate']) ?>">
          <input type="hidden" name="amount" value="<?= htmlspecialchars($ordrow['amount']) ?>">
          <input type="hidden" name="amt" value="<?= htmlspecialchars($ordrow['amt']) ?>">
          <input type="text" name="signa" class="form-control" value="<?= htmlspecialchars($ordrow['signa']) ?>">

          <button type="submit" name="action" class="btn btn-success btn-block">CONFIRM DEPOSIT</button>
        </form>

        <br>
        <form action="" method="post" class="reservation-form mb-0 bg-silver-deep p-30">
          <input type="hidden" name="declineDEP" value="0">
          <input type="hidden" name="log_id" value="<?= $ordrow['log_id'] ?>">
          <button type="submit" name="decline" class="btn btn-danger btn-block">DECLINE DEPOSIT</button>
        </form>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<?php require("footer.php"); ?>
