<?php
// DEBUG MODE - turn on while troubleshooting, turn off after fix
define('DEBUG', false);

if (DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
}

// Load dependencies
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/session.php';

// Require authentication (redirect to login if not)
if (!isAuthenticated()) {
    // If debug, show message instead of immediate redirect to help troubleshooting
    if (DEBUG) {
        echo "<h3>Not authenticated — session missing.</h3>";
        echo "<pre>_SESSION:\n";
        print_r($_SESSION);
        echo "</pre>";
        exit;
    } else {
        header('Location: login.php');
        exit;
    }
}

// get current business
$current_business = getCurrentBusiness();
if (!$current_business) {
    echo "<p style='color:red'>Unable to fetch current business from session.</p>";
    echo "<pre>_SESSION:\n";
    print_r($_SESSION);
    exit;
}

$restaurant_id = $current_business['business_id'];

// Debug info
if (DEBUG) {
    echo "<div style='background:#fff;padding:10px;border:1px solid #ddd;margin:10px 0;'>";
    echo "<strong>Debug:</strong><br>";
    echo "restaurant_id = " . htmlspecialchars($restaurant_id) . "<br>";
    echo "</div>";
}

// --- Fetch subscription ---
// Get latest subscription for this restaurant
try {
    $subscription = one("SELECT * FROM subscriptions WHERE restaurant_id = ? ORDER BY id DESC LIMIT 1", [$restaurant_id]);
} catch (Exception $e) {
    echo "<p style='color:red'>DB error while fetching subscription: " . htmlspecialchars($e->getMessage()) . "</p>";
    $subscription = null;
}

// --- Fetch settings ---
// NOTE: many projects store settings per restaurant using `restaurant_id` rather than `id`.
// If your settings table uses `id` as primary but not equal to restaurant_id, adjust accordingly.
// Try fetching by restaurant_id first, then fallback to id = 1.
try {
    // Fetch settings using the business ID (id column)
try {
    $settings = one("SELECT * FROM settings WHERE id = ? LIMIT 1", [$restaurant_id]);
} catch (Exception $e) {
    echo "<p style='color:red'>DB error while fetching settings: " . htmlspecialchars($e->getMessage()) . "</p>";
    $settings = [];
}

} catch (Exception $e) {
    echo "<p style='color:red'>DB error while fetching settings: " . htmlspecialchars($e->getMessage()) . "</p>";
    $settings = [];
}

// POST handler - create renewal request
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $amount = trim($_POST['amount'] ?? '');
    $mode = trim($_POST['mode'] ?? '');
    $txn = trim($_POST['transaction_id'] ?? '');
    $file = '';

    if (!empty($_FILES['screenshot']['name'])) {
    $uploadDir = __DIR__ . '/../uploads/';
    if (!file_exists($uploadDir)) mkdir($uploadDir, 0755, true);

    $filename = time() . "_" . basename($_FILES['screenshot']['name']);
    $absolutePath = $uploadDir . $filename;

    if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $absolutePath)) {
        // store relative path only
        $file = 'uploads/' . $filename;
    }
}


    // Insert request
    query("INSERT INTO payment_requests (restaurant_id, amount, mode, transaction_id, screenshot, status)
           VALUES (?, ?, ?, ?, ?, 'pending')", [$restaurant_id, $amount, $mode, $txn, $file]);

    logActivity('renewal_request', 'Submitted renewal request for amount: ' . $amount);
    echo "<p style='color:green;'>✅ Request sent! Please wait for admin approval.</p>";
    // Avoid further processing if you want immediate visible result
}

// Render page HTML (unchanged UI)
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscription Renewal - <?= htmlspecialchars($settings['business_name'] ?? 'Restaurant') ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
    <style>
        body {
            background-image: url("<?= defined('BASE_URL') ? BASE_URL : '' ?>/public/background.jpg");
            background-size: cover;
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-position: center;
        }
        .container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 16px;
            padding: 2rem;
            box-shadow: 0 10px 30px rgba(0, 0, 0, .15);
            backdrop-filter: blur(2px);
            margin-top: 2rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8">
                <h2>Subscription Renewal Request</h2>
                <p class="text-muted">Business: <strong><?= htmlspecialchars($settings['business_name'] ?? $current_business['business_name'] ?? 'Unknown') ?></strong></p>
                
                <?php if ($subscription): ?>
                    <div class="alert alert-info">
                        <h5>Current Subscription Status</h5>
                        <p><strong>Plan:</strong> <?= htmlspecialchars($subscription['plan']) ?></p>
                        <p><strong>Status:</strong> 
                            <span class="badge bg-<?= ($subscription['status'] === 'active') ? 'success' : 'danger' ?>">
                                <?= strtoupper(htmlspecialchars($subscription['status'])) ?>
                            </span>
                        </p>
                        <p><strong>Expires:</strong> <?= date('M d, Y', strtotime($subscription['expiry_date'])) ?></p>
                    </div>
                <?php else: ?>
                    <div class="alert alert-warning">
                        <h5>No Active Subscription</h5>
                        <p>You don't have an active subscription. Please submit a renewal request.</p>
                    </div>
                <?php endif; ?>

                <form method="POST" enctype="multipart/form-data" class="mt-4">
                    <div class="mb-3">
                        <label class="form-label">Amount (₹)</label>
                        <input type="number" name="amount" class="form-control" placeholder="Enter amount" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Payment Mode</label>
                        <select name="mode" class="form-select" required>
                            <option value="">Select Payment Mode</option>
                            <option value="UPI">UPI</option>
                            <option value="Bank Transfer">Bank Transfer</option>
                            <option value="Cash">Cash</option>
                            <option value="Card">Card</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Transaction ID</label>
                        <input type="text" name="transaction_id" class="form-control" placeholder="Enter transaction ID" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Payment Screenshot (Optional)</label>
                        <input type="file" name="screenshot" class="form-control" accept="image/*">
                        <div class="form-text">Upload a screenshot of your payment confirmation</div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Submit Renewal Request</button>
                    <a href="index.php" class="btn btn-secondary">Back to Dashboard</a>
                </form>
            </div>
            
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5>Renewal Instructions</h5>
                    </div>
                    <div class="card-body">
                        <ol>
                            <li>Make payment for your subscription</li>
                            <li>Fill in the payment details</li>
                            <li>Upload payment screenshot (optional)</li>
                            <li>Submit the request</li>
                            <li>Wait for admin approval</li>
                        </ol>
                        <div class="alert alert-light">
                            <small><strong>Note:</strong> Your subscription will be renewed for 1 month after approval.</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

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