<?php
/**
 * Payment Page for Land View Access
 * Handles payment processing for unlimited land viewing
 */
define('APP_RUNNING', true);
session_start();
require_once 'db_connect.php';
require_once 'includes/auth.php';

// Require authentication
if(!isset($_SESSION['user_id'])) {
    header('Location: login');
    exit;
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'] ?? 'user';

// Get land_id from query
$land_id = isset($_GET['land_id']) ? intval($_GET['land_id']) : 0;
$payment_type = isset($_GET['type']) ? $_GET['type'] : 'view_access';

if($land_id <= 0) {
    header('Location: lands.php?error=Invalid land');
    exit;
}

// Get land details
$land = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM lands WHERE id = $land_id AND user_id = $user_id"));
if(!$land) {
    header('Location: lands.php?error=Land not found or access denied');
    exit;
}

// Get current view count
$viewResult = mysqli_query($conn, "SELECT * FROM land_views WHERE land_id = $land_id AND user_id = $user_id");
$viewRecord = mysqli_fetch_assoc($viewResult);
$current_views = $viewRecord ? $viewRecord['view_count'] : 0;
$is_paid = $viewRecord ? $viewRecord['is_paid'] : 0;

// Payment amount (in TZS)
$payment_amount = 20000;

// Process payment (simple simulation for now)
$payment_success = false;
$payment_error = '';

if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['process_payment'])) {
    $payment_method = $_POST['payment_method'] ?? 'mobile_money';
    $phone_number = mysqli_real_escape_string($conn, $_POST['phone_number'] ?? '');

    // Generate payment reference
    $payment_reference = 'PAY-' . strtoupper(substr(md5(time() . $user_id . $land_id), 0, 10));

    // In a real implementation, you would integrate with payment gateway here
    // For now, we'll simulate a successful payment

    // Update land_views table to mark as paid
    if($viewRecord) {
        $sql = "UPDATE land_views SET
                    is_paid = 1,
                    payment_date = NOW(),
                    payment_amount = $payment_amount,
                    payment_reference = '$payment_reference'
                WHERE land_id = $land_id AND user_id = $user_id";
    } else {
        $sql = "INSERT INTO land_views (land_id, user_id, view_count, is_paid, payment_date, payment_amount, payment_reference)
                VALUES ($land_id, $user_id, 0, 1, NOW(), $payment_amount, '$payment_reference')";
    }

    if(mysqli_query($conn, $sql)) {
        $payment_success = true;

        // Log the payment
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        mysqli_query($conn, "INSERT INTO activity_logs (user_id, action, description, ip_address)
                             VALUES ($user_id, 'payment', 'Land view access payment - Ref: $payment_reference', '$ip')");
    } else {
        $payment_error = 'Failed to process payment. Please try again.';
    }
}

// Get user details
$user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM users WHERE id = $user_id"));
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lipa Ada - Land Secure</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo url('assets/font-awesome/css/all.min.css'); ?>">
    <link href="<?php echo url('assets/vendor/bootstrap/css/bootstrap.min.css'); ?>" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        :root { --primary: #1a3a6e; --secondary: #2d5a3d; --success: #22c55e; }
        body { background: linear-gradient(135deg, #f0f4f8 0%, #e2e8f0 100%); min-height: 100vh; }

        .payment-container {
            max-width: 600px;
            margin: 40px auto;
            padding: 20px;
        }

        .payment-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .payment-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .payment-header h1 {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 10px;
        }

        .payment-header p {
            opacity: 0.9;
            font-size: 14px;
            margin: 0;
        }

        .land-info {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 12px;
            padding: 15px;
            margin-top: 20px;
        }

        .land-info .land-name {
            font-weight: 600;
            font-size: 16px;
        }

        .land-info .land-id {
            font-size: 12px;
            opacity: 0.8;
        }

        .payment-body {
            padding: 30px;
        }

        .amount-display {
            text-align: center;
            padding: 25px;
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            border-radius: 15px;
            margin-bottom: 25px;
        }

        .amount-display .label {
            color: #92400e;
            font-size: 14px;
            font-weight: 500;
        }

        .amount-display .amount {
            font-size: 42px;
            font-weight: 700;
            color: #78350f;
        }

        .amount-display .currency {
            font-size: 18px;
            color: #92400e;
        }

        .amount-display .period {
            color: #92400e;
            font-size: 14px;
        }

        .benefits-list {
            background: #f8fafc;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
        }

        .benefits-list h4 {
            font-size: 14px;
            font-weight: 600;
            color: #334155;
            margin-bottom: 15px;
        }

        .benefits-list ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .benefits-list li {
            padding: 10px 0;
            color: #475569;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 12px;
            border-bottom: 1px solid #e2e8f0;
        }

        .benefits-list li:last-child {
            border-bottom: none;
        }

        .benefits-list li i {
            color: var(--success);
            width: 20px;
            font-size: 16px;
        }

        .payment-method {
            margin-bottom: 20px;
        }

        .payment-method label {
            font-weight: 600;
            color: #334155;
            margin-bottom: 10px;
            display: block;
        }

        .method-options {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .method-option {
            flex: 1;
            min-width: 120px;
            padding: 15px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .method-option:hover {
            border-color: var(--primary);
        }

        .method-option.selected {
            border-color: var(--primary);
            background: rgba(26, 58, 110, 0.05);
        }

        .method-option img {
            height: 30px;
            margin-bottom: 8px;
        }

        .method-option span {
            display: block;
            font-size: 12px;
            color: #64748b;
        }

        .phone-input {
            margin-bottom: 25px;
        }

        .phone-input label {
            font-weight: 600;
            color: #334155;
            margin-bottom: 8px;
            display: block;
        }

        .phone-input input {
            width: 100%;
            padding: 15px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        .phone-input input:focus {
            outline: none;
            border-color: var(--primary);
        }

        .btn-pay {
            width: 100%;
            padding: 18px;
            background: linear-gradient(135deg, var(--success) 0%, #16a34a 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .btn-pay:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(34, 197, 94, 0.4);
        }

        .btn-pay:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .btn-back {
            display: block;
            text-align: center;
            margin-top: 20px;
            color: #64748b;
            text-decoration: none;
            font-size: 14px;
        }

        .btn-back:hover {
            color: var(--primary);
        }

        /* Success State */
        .success-container {
            text-align: center;
            padding: 40px 30px;
        }

        .success-icon {
            width: 100px;
            height: 100px;
            background: linear-gradient(135deg, var(--success) 0%, #16a34a 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            font-size: 48px;
            color: white;
            animation: successPop 0.5s ease;
        }

        @keyframes successPop {
            0% { transform: scale(0); }
            50% { transform: scale(1.2); }
            100% { transform: scale(1); }
        }

        .success-container h2 {
            color: #1e293b;
            font-size: 24px;
            margin-bottom: 10px;
        }

        .success-container p {
            color: #64748b;
            font-size: 15px;
            margin-bottom: 25px;
        }

        .success-container .ref-number {
            background: #f8fafc;
            padding: 15px;
            border-radius: 10px;
            font-family: monospace;
            font-size: 16px;
            color: var(--primary);
            margin-bottom: 25px;
        }

        .btn-continue {
            display: inline-flex;
            align-items: center;
            gap: 10px;
            padding: 15px 40px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            text-decoration: none;
            border-radius: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-continue:hover {
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(26, 58, 110, 0.3);
        }

        /* Already Paid State */
        .already-paid {
            text-align: center;
            padding: 40px 30px;
        }

        .already-paid-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 36px;
            color: white;
        }

        @media (max-width: 576px) {
            .payment-container {
                padding: 15px;
                margin: 20px auto;
            }
            .amount-display .amount {
                font-size: 32px;
            }
        }
    </style>
</head>
<body>
    <div class="payment-container">
        <div class="payment-card">
            <?php if($payment_success): ?>
            <!-- Payment Success -->
            <div class="success-container">
                <div class="success-icon">
                    <i class="fas fa-check"></i>
                </div>
                <h2>Malipo Yamefanikiwa!</h2>
                <p>Sasa unaweza kutazama ardhi yako bila kikomo kwa mwaka mzima.</p>
                <div class="ref-number">
                    <small>Nambari ya Malipo:</small><br>
                    <?php echo $payment_reference; ?>
                </div>
                <a href="view-land?id=<?php echo $land_id; ?>" class="btn-continue">
                    <i class="fas fa-eye"></i> Tazama Ardhi Yako
                </a>
            </div>

            <?php elseif($is_paid): ?>
            <!-- Already Paid -->
            <div class="already-paid">
                <div class="already-paid-icon">
                    <i class="fas fa-infinity"></i>
                </div>
                <h2>Tayari Umelipa!</h2>
                <p>Una maoni yasiyo na kikomo kwa ardhi hii.</p>
                <?php if($viewRecord['payment_reference']): ?>
                <div class="ref-number">
                    <small>Nambari ya Malipo:</small><br>
                    <?php echo htmlspecialchars($viewRecord['payment_reference']); ?>
                </div>
                <?php endif; ?>
                <a href="view-land?id=<?php echo $land_id; ?>" class="btn-continue">
                    <i class="fas fa-eye"></i> Tazama Ardhi Yako
                </a>
            </div>

            <?php else: ?>
            <!-- Payment Form -->
            <div class="payment-header">
                <h1><i class="fas fa-credit-card mr-2"></i>Lipa Ada ya Kutazama</h1>
                <p>Fungua maoni yasiyo na kikomo kwa ardhi yako</p>

                <div class="land-info">
                    <div class="land-name"><?php echo htmlspecialchars($land['land_name']); ?></div>
                    <div class="land-id">ID: LS-<?php echo str_pad($land['id'], 5, '0', STR_PAD_LEFT); ?></div>
                </div>
            </div>

            <div class="payment-body">
                <?php if($payment_error): ?>
                <div class="alert alert-danger mb-4">
                    <i class="fas fa-exclamation-circle mr-2"></i><?php echo $payment_error; ?>
                </div>
                <?php endif; ?>

                <div class="amount-display">
                    <div class="label">Kiasi cha Kulipa</div>
                    <div class="amount">20,000 <span class="currency">TZS</span></div>
                    <div class="period">kwa mwaka mmoja</div>
                </div>

                <div class="benefits-list">
                    <h4><i class="fas fa-gift mr-2"></i>Utapata:</h4>
                    <ul>
                        <li><i class="fas fa-check-circle"></i> Maoni yasiyo na kikomo kwa mwaka mzima</li>
                        <li><i class="fas fa-check-circle"></i> Pakua cheti cha ardhi (PDF)</li>
                        <li><i class="fas fa-check-circle"></i> Angalia ramani ya satellite</li>
                        <li><i class="fas fa-check-circle"></i> Shiriki ardhi na wengine kupitia link</li>
                        <li><i class="fas fa-check-circle"></i> Barua pepe na SMS za arifa</li>
                    </ul>
                </div>

                <form method="POST" id="paymentForm">
                    <div class="payment-method">
                        <label>Njia ya Malipo</label>
                        <div class="method-options">
                            <div class="method-option selected" data-method="mpesa" onclick="selectMethod(this, 'mpesa')">
                                <i class="fas fa-mobile-alt fa-2x" style="color: #4caf50;"></i>
                                <span>M-Pesa</span>
                            </div>
                            <div class="method-option" data-method="tigopesa" onclick="selectMethod(this, 'tigopesa')">
                                <i class="fas fa-mobile-alt fa-2x" style="color: #0066b3;"></i>
                                <span>Tigo Pesa</span>
                            </div>
                            <div class="method-option" data-method="airtel" onclick="selectMethod(this, 'airtel')">
                                <i class="fas fa-mobile-alt fa-2x" style="color: #ed1c24;"></i>
                                <span>Airtel Money</span>
                            </div>
                        </div>
                        <input type="hidden" name="payment_method" id="paymentMethod" value="mpesa">
                    </div>

                    <div class="phone-input">
                        <label><i class="fas fa-phone mr-2"></i>Nambari ya Simu</label>
                        <input type="tel" name="phone_number" placeholder="0712 345 678"
                               value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" required>
                    </div>

                    <button type="submit" name="process_payment" class="btn-pay" id="payBtn">
                        <i class="fas fa-lock"></i> Lipa TZS 20,000
                    </button>
                </form>

                <a href="view-land?id=<?php echo $land_id; ?>" class="btn-back">
                    <i class="fas fa-arrow-left mr-2"></i> Rudi Nyuma
                </a>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
    function selectMethod(element, method) {
        document.querySelectorAll('.method-option').forEach(el => el.classList.remove('selected'));
        element.classList.add('selected');
        document.getElementById('paymentMethod').value = method;
    }

    document.getElementById('paymentForm')?.addEventListener('submit', function(e) {
        const btn = document.getElementById('payBtn');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Inaendelea...';
    });
    </script>
</body>
</html>
