<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../src/db.php';
date_default_timezone_set('Asia/Kolkata'); 
require_once __DIR__ . '/../src/session.php';

// Simple admin authentication (can be enhanced)
$admin_password = 'admin123'; // change to a secure one
$is_admin = false;

// ============================
// ADMIN LOGIN
// ============================
if (isset($_POST['admin_login'])) {
    if ($_POST['admin_password'] === $admin_password) {
        $_SESSION['admin_logged_in'] = true;
        $is_admin = true;
    } else {
        $error = "Invalid admin password.";
    }
} elseif (!empty($_SESSION['admin_logged_in'])) {
    $is_admin = true;
}

// ============================
// LOGOUT
// ============================
if (isset($_GET['logout'])) {
    unset($_SESSION['admin_logged_in']);
    $is_admin = false;
}

// ============================
// HANDLE ADMIN ACTIONS
// ============================
if ($is_admin) {
    try {

        // ============================
        // APPROVE REQUEST (FINAL LOGIC)
        // ============================
        if (isset($_GET['approve'])) {

            $id = intval($_GET['approve']);
            $payment = one("SELECT * FROM payment_requests WHERE id = ?", [$id]);

            if ($payment) {
                $rid = $payment['restaurant_id'];

                // Approval timestamp (NOW)
                $start_date = date('Y-m-d H:i:s');

                // Expiry = +1 month from NOW
                $expiry_date = date('Y-m-d H:i:s', strtotime($start_date . ' +1 month'));

                // Check if subscription exists
                $sub = one("SELECT * FROM subscriptions WHERE restaurant_id = ?", [$rid]);

                if ($sub) {
                    // Update existing subscription
                    query("UPDATE subscriptions 
                        SET start_date = ?, expiry_date = ?, status = 'active'
                        WHERE restaurant_id = ?",
                        [$start_date, $expiry_date, $rid]);

                } else {
                    // Create new subscription
                    query("INSERT INTO subscriptions (restaurant_id, start_date, expiry_date, status)
                        VALUES (?, ?, ?, 'active')",
                        [$rid, $start_date, $expiry_date]);
                }

                // Mark payment request as approved
                query("UPDATE payment_requests SET status = 'approved' WHERE id = ?", [$id]);

                echo "<div class='alert alert-success'>
                        ✅ Subscription activated<br>
                        Start: <strong>$start_date</strong><br>
                        Expiry: <strong>$expiry_date</strong>
                    </div>";
            }
        }



        // ============================
        // REJECT REQUEST
        // ============================
        if (isset($_GET['reject'])) {
            $id = intval($_GET['reject']);
            query("UPDATE payment_requests SET status = 'rejected' WHERE id = ?", [$id]);
            echo "<div class='alert alert-danger'>❌ Request Rejected</div>";
        }

        // ============================
        // FETCH PENDING REQUESTS
        // ============================
        $pending = all_rows("
            SELECT pr.*, s.business_name 
            FROM payment_requests pr
            LEFT JOIN settings s ON pr.restaurant_id = s.id
            WHERE pr.status = 'pending'
            ORDER BY pr.id DESC
        ");

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

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Renewal Approvals</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
</head>
<body class="bg-light">
<div class="container mt-4">

<?php if (!$is_admin): ?>

    <!-- Admin Login -->
    <div class="row justify-content-center">
        <div class="col-md-4">
            <div class="card shadow-lg">
                <div class="card-header bg-primary text-white text-center">
                    <h4>Admin Login</h4>
                </div>
                <div class="card-body">
                    <?php if (isset($error)): ?>
                        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label">Admin Password</label>
                            <input type="password" name="admin_password" class="form-control" required>
                        </div>
                        <button type="submit" name="admin_login" class="btn btn-success w-100">Login</button>
                    </form>

                </div>
            </div>
        </div>
    </div>

<?php else: ?>

    <!-- Admin Dashboard -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Pending Renewal Requests</h2>
        <a href="?logout=1" class="btn btn-outline-danger">Logout</a>
    </div>

    <?php if (empty($pending)): ?>
        <div class="alert alert-info">
            <h5>No Pending Requests</h5>
            <p>There are currently no pending renewal requests.</p>
        </div>
    <?php else: ?>

        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover align-middle">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Business Name</th>
                        <th>Restaurant ID</th>
                        <th>Amount</th>
                        <th>Mode</th>
                        <th>Transaction ID</th>
                        <th>Screenshot</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>

                <tbody>
                <?php foreach ($pending as $p): ?>
                    <tr>
                        <td><?= htmlspecialchars($p['id']) ?></td>
                        <td><?= htmlspecialchars($p['business_name'] ?? 'Unknown') ?></td>
                        <td><?= htmlspecialchars($p['restaurant_id']) ?></td>
                        <td>₹ <?= number_format($p['amount'], 2) ?></td>
                        <td><?= htmlspecialchars($p['mode']) ?></td>
                        <td><code><?= htmlspecialchars($p['transaction_id']) ?></code></td>

                        <td>
                            <?php if (!empty($p['screenshot'])): ?>
                                <a href="<?= BASE_URL . '/' . $p['screenshot'] ?>" target="_blank" class="btn btn-sm btn-outline-primary">View</a>
                            <?php else: ?>
                                <span class="text-muted">No screenshot</span>
                            <?php endif; ?>
                        </td>

                        <td><?= date('M d, Y H:i', strtotime($p['created_at'] ?? 'now')) ?></td>

                        <td>
                            <a href="?approve=<?= $p['id'] ?>"
                               class="btn btn-sm btn-success"
                               onclick="return confirm('Approve this renewal request?')">✅ Approve</a>

                            <a href="?reject=<?= $p['id'] ?>"
                               class="btn btn-sm btn-danger"
                               onclick="return confirm('Reject this renewal request?')">❌ Reject</a>
                        </td>

                    </tr>
                <?php endforeach; ?>
                </tbody>

            </table>
        </div>

    <?php endif; ?>
<?php endif; ?>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>
