<?php

$pageName = "Edit Deposit Transactions";
include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/header.php");

// ---------------------------------------------------------
// Validate & fetch transaction
// ---------------------------------------------------------
$id = isset($_GET['id']) ? trim($_GET['id']) : '';

if ($id === '') {
    header("Location: ./deposit.php");
    exit;
}

// Fetch transaction + user info
$sql = "SELECT transactions.*, users.* 
        FROM transactions 
        LEFT JOIN users ON transactions.user_id = users.id 
        WHERE transactions.refrence_id = :id";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$result) {
    echo "<div class='alert alert-danger'>Transaction not found.</div>";
    include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/footer.php");
    exit;
}

$transStatus = TranStatus($result);
$user_id     = $result['id']; // users.id (because of LEFT JOIN order)

// Fetch crypto info using LEFT JOIN so it still returns even if crypto record is missing
$sql = "SELECT d.*, c.crypto_name 
        FROM transactions d 
        LEFT JOIN crypto_currency c ON d.crypto_id = c.id 
        WHERE d.refrence_id = :id";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    $row = ['amount' => 0, 'crypto_name' => 'N/A', 'trans_id' => ''];
}

$fullName = $result['firstname'] . " " . $result['lastname'];
$amount   = isset($row['amount']) ? (float)$row['amount'] : 0;

// ---------------------------------------------------------
// Helper to update transaction status & notify user
// ---------------------------------------------------------
function updateTransactionStatus($conn, $id, $status_value, $sendMail, $email_message, $result, $row, $page, $updateBalance = false) {
    $success = false;

    try {
        $conn->beginTransaction();

        // Update transaction status
        $sql = "UPDATE transactions SET trans_status = :status WHERE refrence_id = :id";
        $stmt = $conn->prepare($sql);
        $stmt->execute([
            'status' => $status_value,
            'id'     => $id
        ]);

        // If accepting, credit the user's balance
        if ($updateBalance) {
            $newBalance = (float)$row['amount'] + (float)$result['acct_balance'];
            $sql = "UPDATE users SET acct_balance = :acct_balance WHERE id = :id";
            $stmt = $conn->prepare($sql);
            $stmt->execute([
                'acct_balance' => $newBalance,
                'id'           => $result['id']
            ]);
        }

        $conn->commit();
        $success = true;
    } catch (Exception $e) {
        $conn->rollBack();
        return false;
    }

    if ($success) {
        // Send notification email
        $full_name    = $result['firstname'] . " " . $result['lastname'];
        $amount       = $row['amount'];
        $user_balance = $result['acct_balance'];
        $user_acctno  = $result['acct_no'];
        $APP_NAME     = WEB_TITLE;
        $APP_URL      = WEB_URL;
        $SITE_ADDRESS = $page['url_address'];
        $user_email   = $result['acct_email'];
        $trans_type   = "Deposit";

        $message = $sendMail->AdminFundingMsg(
            $full_name,
            $amount,
            $user_balance,
            $user_acctno,
            $status_value,
            $trans_type,
            $APP_NAME,
            $APP_URL,
            $SITE_ADDRESS
        );

        $subject = "Deposit - " . $APP_NAME;
        $email_message->send_mail($user_email, $message, $subject);
    }

    return $success;
}

// ---------------------------------------------------------
// Handle POST actions
// ---------------------------------------------------------
$msg1 = '';

function buildSuccessMessage() {
    return "
        <div class='alert alert-warning'>
            <script type='text/javascript'>
                function Redirect() {
                    window.location='./deposit.php';
                }
                setTimeout('Redirect()', 3000);
            </script>
            <center><img src='../assets/images/loading.gif' width='180px' /></center>
            <center><strong style='color:black;'>Successful! Please wait while we redirect you...</strong></center>
        </div>
    ";
}

if (isset($_POST['accept'])) {
    if (updateTransactionStatus($conn, $id, 'completed', $sendMail, $email_message, $result, $row, $page, true)) {
        $msg1 = buildSuccessMessage();
    } else {
        toast_alert('error', 'Sorry, something went wrong');
    }
}

if (isset($_POST['decline'])) {
    if (updateTransactionStatus($conn, $id, 'failed', $sendMail, $email_message, $result, $row, $page, false)) {
        $msg1 = buildSuccessMessage();
    } else {
        toast_alert('error', 'Sorry, something went wrong');
    }
}

if (isset($_POST['hold'])) {
    if (updateTransactionStatus($conn, $id, 'processing', $sendMail, $email_message, $result, $row, $page, false)) {
        $msg1 = buildSuccessMessage();
    } else {
        toast_alert('error', 'Sorry, something went wrong');
    }
}

?>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>Edit Deposit Transactions</h1>
        <ol class="breadcrumb">
            <li><a href="./dashboard.php"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        </ol>
    </section>

    <!-- Main content -->
    <section class="content">

        <div class="box box-default">
            <form method="POST">
                <div class="box-header with-border">
                    <div class="box-tools pull-right">
                        <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                    </div>
                </div>
                <!-- /.box-header -->
                <div class="box-body">
                    <div class="row">

                        <?php if (!empty($msg1)) echo $msg1; ?>

                        <div class="col-md-6">
                            <table class="table table-bordered mb-4">
                                <tbody>
                                    <tr>
                                        <th>Name</th>
                                        <th><?= htmlspecialchars(ucwords($fullName)) ?></th>
                                    </tr>
                                    <tr>
                                        <th>Amount</th>
                                        <th><?= htmlspecialchars($currency) ?><?= htmlspecialchars($result['amount']) ?></th>
                                    </tr>
                                    <tr>
                                        <th>Transaction ID</th>
                                        <th><?= htmlspecialchars($result['refrence_id']) ?></th>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <div class="col-md-6">
                            <table class="table table-bordered mb-4">
                                <tbody>
                                    <tr>
                                        <th>Crypto Name</th>
                                        <th><?= !empty($row['crypto_name']) ? htmlspecialchars($row['crypto_name']) : 'N/A' ?></th>
                                    </tr>
                                    <tr>
                                        <th>Receipt</th>
                                        <th>
                                            <?php if (!empty($result['image'])): ?>
                                                <a href="<?= htmlspecialchars($web_url) ?>/assets/deposit/<?= htmlspecialchars($result['image']) ?>" target="_blank">
                                                    <img src="<?= htmlspecialchars($web_url) ?>/assets/deposit/<?= htmlspecialchars($result['image']) ?>" width="20%" alt="Receipt">
                                                </a>
                                            <?php else: ?>
                                                <span class="text-muted">No receipt uploaded</span>
                                            <?php endif; ?>
                                        </th>
                                    </tr>
                                    <tr>
                                        <th>Created At</th>
                                        <th><?= htmlspecialchars($result['created_at']) ?></th>
                                    </tr>
                                    <tr>
                                        <th>Status</th>
                                        <th><?= $transStatus ?></th>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>
                <!-- /.box-body -->

                <div class="box-footer">
                    <button type="submit" name="accept" class="btn btn-success">Accept</button>
                    <button type="submit" name="hold" class="btn btn-warning">Hold</button>
                    <button type="submit" name="decline" class="btn btn-danger">Decline</button>
                </div>
            </form>
        </div>

    </section>
    <!-- /.content -->
</div>
<!-- /.content-wrapper -->

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/footer.php");
?>