<?php
date_default_timezone_set('Asia/Kolkata');
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Database configuration
$config = include($_SERVER['DOCUMENT_ROOT'] . "/pay/config.php");
$conn = new mysqli(
    $config['db_host'],
    $config['db_user'],
    $config['db_pass'],
    $config['db_name']
);

if ($conn->connect_error) {
    die("❌ DB Connection failed: " . $conn->connect_error);
}

// Handle UTR submission if POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['utr_no'])) {
    // Validate inputs
    $order_no = isset($_POST['order_no']) ? $conn->real_escape_string($_POST['order_no']) : die("❌ Invalid Order No");
    $utr_no = isset($_POST['utr_no']) ? preg_replace('/[^0-9]/', '', $_POST['utr_no']) : die("❌ Invalid UTR");

    // Validate UTR length
    if (strlen($utr_no) != 12) {
        die("❌ UTR must be 12 digits");
    }

    // Update thevani table with UTR number
    $update_query = $conn->prepare("UPDATE thevani SET ullekha = ? WHERE dharavahi = ?");
    $update_query->bind_param("ss", $utr_no, $order_no);

    if (!$update_query->execute()) {
        die("❌ UTR update failed: " . $conn->error);
    }

    // Update transaction status
    $conn->query("UPDATE transactions SET status = 'processing' WHERE order_no = '$order_no'");
    $conn->query("UPDATE recharge SET status = 'processing' WHERE orderid = '$order_no'");

    header("Location: success.php?order_no=" . $order_no);
    exit();
}

// Handle payment initiation if GET request
$uid = isset($_GET['uid']) && is_numeric($_GET['uid']) ? (int)$_GET['uid'] : die("❌ Invalid UID");
$input_amount = isset($_GET['amount']) && is_numeric($_GET['amount']) ? (float)$_GET['amount'] : die("❌ Invalid Amount");

// Get mobile number from shonu_subjects
$mobile_query = $conn->prepare("SELECT mobile FROM shonu_subjects WHERE id = ?");
$mobile_query->bind_param("i", $uid);
$mobile_query->execute();
$mobile_result = $mobile_query->get_result();

if ($mobile_result->num_rows === 0) {
    die("❌ User not found in shonu_subjects");
}

$user_data = $mobile_result->fetch_assoc();
$mobile_number = $user_data['mobile'];

// Format amounts
$recharge_amount = number_format($input_amount, 2, '.', '');
$pay_amount = $recharge_amount;

// Get UPI ID
$res_upi = $conn->query("SELECT maulya FROM deyya WHERE sthiti='1' LIMIT 1");
if (!$res_upi) die("❌ UPI ID query failed: " . $conn->error);
$upi_row = $res_upi->fetch_assoc();
$upi_id = $upi_row['maulya'] ?? 'default@upi';
$upi_name = 'FastPay';

// Generate order details
$order_no = "ORD" . time() . rand(100, 999);
$upi_link = "upi://pay?pa=$upi_id&pn=$upi_name&am=$pay_amount&cu=INR";

// Generate QR code
include($_SERVER['DOCUMENT_ROOT'] . "/pay/phpqrcode/qrlib.php");
$qr_dir = __DIR__ . "/qr/";
if (!is_dir($qr_dir)) mkdir($qr_dir, 0777, true);
$qr_path = $qr_dir . $order_no . ".png";
QRcode::png($upi_link, $qr_path, QR_ECLEVEL_H, 6);

// Insert into transactions table
if (!$conn->query("INSERT INTO transactions (order_no, uid, amount, status, created_at) 
    VALUES ('$order_no', '$uid', '$pay_amount', 'pending', NOW())")) {
    die("❌ Transaction insert failed: " . $conn->error);
}

// Insert into recharge table
if (!$conn->query("INSERT INTO recharge (uid, orderid, amount, status, created_at) 
    VALUES ('$uid', '$order_no', '$recharge_amount', 'pending', NOW())")) {
    die("❌ Recharge insert failed: " . $conn->error);
}

// Insert into thevani table with mobile number
if (!$conn->query("INSERT INTO thevani 
    (balakedara, dharavahi, mula, sthiti, dinankavannuracisi, motta, duravani) 
    VALUES 
    ('$uid', '$order_no', '$recharge_amount', 0, NOW(), '$recharge_amount', '$mobile_number')")) {
    die("❌ Thevani insert failed: " . $conn->error);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secure Payment | FastPay</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #4f46e5;
            --primary-dark: #4338ca;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --gray-100: #f3f4f6;
            --gray-200: #e5e7eb;
            --gray-300: #d1d5db;
            --gray-400: #9ca3af;
            --gray-500: #6b7280;
            --gray-600: #4b5563;
            --gray-700: #374151;
            --gray-800: #1f2937;
            --gray-900: #111827;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background-color: #f9fafb;
            color: var(--gray-800);
            line-height: 1.5;
        }
        
        .payment-container {
            max-width: 480px;
            margin: 2rem auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }
        
        .payment-header {
            padding: 1.5rem;
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: white;
            text-align: center;
        }
        
        .payment-header h1 {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 0.25rem;
        }
        
        .payment-body {
            padding: 1.5rem;
        }
        
        .amount-display {
            text-align: center;
            margin-bottom: 1.5rem;
        }
        
        .amount-label {
            font-size: 0.875rem;
            color: var(--gray-500);
            margin-bottom: 0.25rem;
        }
        
        .amount-value {
            font-size: 2rem;
            font-weight: 700;
            color: var(--gray-900);
        }
        
        .order-info {
            background: var(--gray-100);
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            font-size: 0.875rem;
        }
        
        .order-info p {
            margin-bottom: 0.5rem;
            display: flex;
            justify-content: space-between;
        }
        
        .order-info span:last-child {
            font-weight: 500;
        }
        
        .qr-container {
            text-align: center;
            margin: 1.5rem 0;
            padding: 1rem;
            background: white;
            border-radius: 12px;
            border: 1px solid var(--gray-200);
        }
        
        .qr-container img {
            width: 200px;
            height: 200px;
            margin: 0 auto;
        }
        
        .qr-instruction {
            font-size: 0.875rem;
            color: var(--gray-500);
            margin-top: 0.5rem;
            text-align: center;
        }
        
        .payment-buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.75rem;
            margin: 1.5rem 0;
        }
        
        .payment-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            padding: 0.75rem 1rem;
            border-radius: 8px;
            font-weight: 500;
            color: white;
            text-decoration: none;
            transition: all 0.2s;
        }
        
        .payment-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        
        .payment-btn img {
            width: 24px;
            height: 24px;
        }
        
        .btn-navi {
            background-color: #0d2137;
        }
        
        .btn-bhim {
            background-color: #ff6f00;
        }
        
        .payment-form {
            margin-top: 1.5rem;
        }
        
        .form-group {
            margin-bottom: 1rem;
        }
        
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
            font-weight: 500;
            color: var(--gray-700);
        }
        
        .form-input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid var(--gray-300);
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.2s;
        }
        
        .form-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }
        
        .submit-btn {
            width: 100%;
            padding: 0.875rem;
            background-color: var(--primary);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .submit-btn:hover {
            background-color: var(--primary-dark);
        }
        
        .timer {
            text-align: center;
            margin-top: 1.5rem;
            padding: 0.75rem;
            background-color: #fff4e6;
            border-radius: 8px;
            color: var(--warning);
            font-weight: 500;
        }
        
        .trust-badges {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 1rem;
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 1px solid var(--gray-200);
        }
        
        .trust-badge {
            height: 40px;
            opacity: 0.8;
            transition: opacity 0.2s;
        }
        
        .trust-badge:hover {
            opacity: 1;
        }
        
        @media (max-width: 480px) {
            .payment-container {
                margin: 0;
                border-radius: 0;
            }
            
            .payment-buttons {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="payment-container">
        <div class="payment-header">
            <h1>Secure Payment</h1>
           
        </div>
        
        <div class="payment-body">
            <div class="amount-display">
                <div class="amount-label">Amount to pay</div>
                <div class="amount-value">₹<?php echo htmlspecialchars($recharge_amount); ?></div>
            </div>
            
            <div class="order-info">
                <p>
                    <span>Order ID</span>
                    <span><?php echo $order_no; ?></span>
                </p>
                <p>
                    <span>Date</span>
                    <span><?php echo date('d M Y, h:i A'); ?></span>
                </p>
                <p>
                    <span>Status</span>
                    <span style="color: var(--warning);">Pending</span>
                </p>
            </div>
            
            <div class="qr-container">
                <img src="qr/<?php echo $order_no; ?>.png" alt="UPI QR Code">
                <p class="qr-instruction">Scan this QR code with any UPI app to pay</p>
            </div>
            
            <div class="payment-buttons">
                <a href="<?php echo $upi_link; ?>&tn=Navi" class="payment-btn btn-navi">
                    <img src="logo/navi3.png" alt="Navi">
                    Pay with Navi
                </a>
                <a href="<?php echo $upi_link; ?>&tn=BHIM" class="payment-btn btn-bhim">
                    <img src="logo/bhim1.png" alt="BHIM">
                    Pay with BHIM
                </a>
            </div>
            
            <div class="payment-form">
                <form method="POST" onsubmit="return validateUTR()">
                    <input type="hidden" name="order_no" value="<?php echo $order_no; ?>">
                    
                    <div class="form-group">
                        <label for="utr_no" class="form-label">Enter UTR Number</label>
                        <input type="text" name="utr_no" id="utr_no" class="form-input" 
                               placeholder="12-digit UTR number from your bank" required>
                    </div>
                    
                    <button type="submit" class="submit-btn">Submit Payment Details</button>
                </form>
            </div>
            
            <div class="timer">
                ⏳ Complete payment within <span id="countdown">300</span> seconds
            </div>
            
            <div class="trust-badges">
                <img src="https://razorpay.com/build/browser/static/trust-badges.6c6f79e4.png" 
                     alt="PCI DSS Certified" class="trust-badge">
                <img src="https://razorpay.com/build/browser/static/secure-seal.1d69c8d1.svg" 
                     alt="Secure Seal" class="trust-badge">
            </div>
        </div>
    </div>

    <script>
        let seconds = 300;
        const timerDisplay = document.getElementById('countdown');
        const orderNo = "<?php echo $order_no; ?>";
        
        const countdown = setInterval(() => {
            seconds--;
            timerDisplay.textContent = seconds;
            if (seconds <= 0) {
                clearInterval(countdown);
                window.location.href = "cancel.php?order_no=" + orderNo;
            }
        }, 1000);
        
        function validateUTR() {
            const utr = document.getElementById('utr_no').value.trim();
            if (!/^\d{12}$/.test(utr)) {
                alert("Please enter a valid 12-digit UTR number.");
                return false;
            }
            return true;
        }
        
        setInterval(() => {
            fetch("check_status.php?order_no=" + orderNo)
                .then(res => res.text())
                .then(status => {
                    if (status.trim() === "success") {
                        window.location.href = "success.php?order_no=" + orderNo;
                    }
                });
        }, 5000);
    </script>
</body>
</html>