<?php 
include 'header.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$msg = "";
$err = "";

// Verify database connection
if (!$link) {
    die("Connection failed: " . mysqli_connect_error());
}

if (isset($_GET['app'])) {
    $tid = mysqli_real_escape_string($link, $_GET['app']);

    // Start transaction
    mysqli_begin_transaction($link);

    try {
        // Fetch payment details
        $sq = mysqli_query($link, "SELECT p.*, c.name as celebrity_name, u.email, u.name 
                                 FROM payments p 
                                 LEFT JOIN celebrities c ON p.celebrity_id = c.id
                                 LEFT JOIN users u ON p.userid = u.id
                                 WHERE p.id = '$tid'");
        if ($sq === false) {
            throw new Exception("Query failed: " . mysqli_error($link));
        }
        if (mysqli_num_rows($sq) == 0) {
            throw new Exception("Payment not found");
        }
        
        $rw = mysqli_fetch_assoc($sq);
        $userId = $rw['userid'];
        $amount = $rw['amount'];
        $status = $rw['status'];
        $celebrityName = $rw['celebrity_name'];
        $username = $rw['name'];
        $email = $rw['email'];
        
        if ($status == "Completed") {
            $msg = "This payment has been approved already";
        } else {
            // Update payment status
            $query = mysqli_query($link, "UPDATE payments SET status = 'Completed', updated_at = NOW() WHERE id = '$tid'");
            if (!$query) {
                throw new Exception("Error approving payment: " . mysqli_error($link));
            }

            // Send email
            $subject = "Payment Approved at {$sitename}!";
            $body = "
            <div style='background: #E4E9F0; padding: 20px; font-family: Arial, sans-serif;'>
                <div style='max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);'>
                    <div style='background-color: #1e293b; padding: 16px; display: flex; align-items: center;'>
                        <div style='display: flex; align-items: center;'>
                            <center><img src='$siteurl/logo.png' width='100px' style='margin-right: 8px;'></center>
                        </div>
                    </div>
                    <div style='padding: 32px; text-align: center;'>
                        <h1 style='font-size: 28px; color: #1e293b; margin-bottom: 24px; line-height: 1.2;'>
                            Your Payment Has Been Approved!
                        </h1>
                        <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                            Hi, <b>$username</b>, your payment of $$amount USD for " . ($rw['Event'] ? 'event ' . $rw['event_name'] : 'celebrity ' . $celebrityName) . " has been approved successfully.
                        </p>
                        <p style='font-size: 18px; color: #4b5563; margin-bottom: 24px;'>
                            Thanks for choosing $sitename!
                        </p>
                        <div style='margin-top: 32px; border-top: 1px solid #e5e7eb; padding-top: 24px; text-align: left;'>
                            <p style='color: #4b5563; margin-bottom: 8px;'>If you have any questions, feel free to reach out to us at $sitemail.</p>
                            <p style='color: #4b5563; margin-bottom: 8px;'>Thanks,</p>
                            <p style='color: #4b5563; font-weight: bold;'>Support Team, $sitename</p>
                        </div>
                        <div style='margin-top: 32px; font-size: 12px; color: #6b7280; text-align: left;'>
                            <p style='margin-bottom: 4px;'>Please consider all emails from us as confidential.</p>
                        </div>
                    </div>
                </div>
            </div>";
            
            $send = sendMail($email, $subject, $body);
            
            // Commit transaction if everything succeeded
            mysqli_commit($link);
            
            if (!$send) {
                echo "<script>alert('Payment approved, but mail not sent');window.location.href = 'pending-payment.php'</script>";
            } else {
                echo "<script>alert('Payment approved successfully');window.location.href = 'pending-payment.php'</script>";
            }
        }
    } catch (Exception $e) {
        mysqli_rollback($link);
        $err = $e->getMessage();
        echo "<script>alert('Error: $err');window.location.href = 'pending-payment.php'</script>";
    }
}

if (isset($_GET['del'])) {
    $tid = mysqli_real_escape_string($link, $_GET['del']);
    $del = mysqli_query($link, "DELETE FROM payments WHERE id = '$tid'");
    if ($del) {
        echo "<script>alert('Payment deleted successfully');window.location.href = 'pending-payment.php'</script>";
    } else {
        echo "Error deleting payment: " . mysqli_error($link);
    }
}
?>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.jqueryui.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.jqueryui.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.bootstrap.min.css">

<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/dataTables.jqueryui.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.jqueryui.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.html5.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.colVis.min.js"></script>

<style>
.table-responsive {
    overflow-x: hidden;
}
@media (max-width: 8000px) {
    .table-responsive {
        overflow-x: auto;
    }
}
</style>

<div class="page-content">
    <div class="container-fluid">
        <?php 
        if ($msg != "") {
            echo "<div style='padding:20px;background-color:#dce8f7;color:black'> $msg</div class='btn btn-success'>" ."</br></br>"; 
        }
        if ($err != "") {
            echo customAlert("error", $err);
        }
        ?>
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title mb-0">All Payments</h4>
                    </div>
                    <div class="card-body">
                        <div id="customerList">
                            <div class="table-responsive table-card mt-3 mb-1">
                                <table id="myTable" class="table-responsive">  
                                    <thead class="table-light">
                                        <tr class="info">
                                            <th>User Name</th>
                                            <th>Email</th>
                                            <th>Celebrity</th>
                                            <th>Amount(USD)</th>
                                            <th>Type</th>
                                            <th>Status</th>
                                            <th>Date</th>
                                            <th>Action</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $sql = "SELECT p.*, u.name, u.email, c.name as celebrity_name 
                                                FROM payments p 
                                                LEFT JOIN users u ON p.userid = u.id
                                                LEFT JOIN celebrities c ON p.celebrity_id = c.id
                                                WHERE p.status = 'pending' 
                                                ORDER BY p.id DESC";
                                        $result = mysqli_query($link, $sql);
                                        if ($result === false) {
                                            die("Query failed: " . mysqli_error($link));
                                        }
                                        if (mysqli_num_rows($result) > 0) {
                                            while ($row = mysqli_fetch_assoc($result)) {   
                                        ?>
                                        <tr class="primary">
                                            <form method="post">
                                                <input type="hidden" name="name" value="<?php echo $row['name'] ?>">
                                                <input type="hidden" name="email" value="<?php echo $row['email'] ?>">
                                                <input type="hidden" name="payment_id" value="<?php echo $row['id'] ?>">
                                                <input type="hidden" name="status" value="<?php echo $row['status'] ?>">
                                                <input type="hidden" name="amount" value="<?php echo $row['amount'] ?>">
                                                <input type="hidden" name="userId" value="<?php echo $row['userid'] ?>">
                                                <td><?php echo $row['name'] ?></td>
                                                <td><?php echo $row['email'] ?></td>
                                                <td><?php echo $row['celebrity_name'] ?></td>
                                                <td>$<?php echo $row['amount'] ?></td>
                                                <td><?php echo $row['type'] ?></td>
                                                <td><?php echo $row['status'] ?></td>
                                                <td><?php echo $row['created_at'] ?></td>
                                                <td>
                                                    <a onclick="return confirm('Carry out action')" href="?app=<?php echo $row['id']; ?>" class="btn btn-success">Approve</a>
                                                </td>
                                                <td>
                                                    <a href="?del=<?php echo $row['id']; ?>" class="btn btn-danger">Delete</a>
                                                </td>
                                            </form>
                                        </tr>
                                        <?php
                                            }
                                        }
                                        ?>
                                    </tbody>
                                </table>  
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function(){
    $('#myTable').dataTable();
});
</script>

<?php include 'footer.php'; ?>