<?php
session_start();
if ($_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}
include '../config/db.php';

$message = '';
$error = '';
$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Get user details
$user_query = $conn->query("SELECT * FROM users WHERE id = $user_id");
if ($user_query->num_rows == 0) {
    header("Location: dashboard.php");
    exit();
}
$user = $user_query->fetch_assoc();

// Process KYC rejection
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $rejection_reason = trim($_POST['rejection_reason']);
    
    if (empty($rejection_reason)) {
        $error = "Please provide a reason for rejecting the KYC.";
    } else {
        // Update user KYC status to rejected
        $stmt = $conn->prepare("UPDATE users SET kyc_status = 'rejected', kyc_doc = NULL WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        
        if ($stmt->execute()) {
            // Log the rejection in a new table for history (optional)
            $conn->query("CREATE TABLE IF NOT EXISTS kyc_rejection_logs (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT,
                rejection_reason TEXT,
                rejected_by INT,
                rejected_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
                FOREIGN KEY (rejected_by) REFERENCES users(id) ON DELETE SET NULL
            )");
            
            $stmt2 = $conn->prepare("INSERT INTO kyc_rejection_logs (user_id, rejection_reason, rejected_by) VALUES (?, ?, ?)");
            $stmt2->bind_param("isi", $user_id, $rejection_reason, $_SESSION['user_id']);
            $stmt2->execute();
            $stmt2->close();
            
            $_SESSION['success_msg'] = "KYC for " . htmlspecialchars($user['name']) . " has been rejected.";
            header("Location: dashboard.php");
            exit();
        } else {
            $error = "Database error: " . $conn->error;
        }
        $stmt->close();
    }
}

// Get KYC document preview
function getKycPreview($filePath) {
    if (empty($filePath)) return false;
    $paths = [$filePath, "../" . $filePath, "../assets/uploads/kyc/" . basename($filePath)];
    foreach ($paths as $path) {
        if (file_exists($path)) {
            $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
            $isImage = in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp']);
            return ['exists' => true, 'url' => $path, 'type' => $isImage ? 'image' : 'file', 'ext' => $ext];
        }
    }
    return false;
}

$kyc_doc = getKycPreview($user['kyc_doc']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reject KYC - SHELDANG Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 2rem;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
        }

        /* Header */
        .header {
            background: white;
            border-radius: 20px;
            padding: 1.5rem 2rem;
            margin-bottom: 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }

        .header h1 {
            font-size: 1.8rem;
            color: #dc3545;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .back-btn {
            background: #6c757d;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            text-decoration: none;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .back-btn:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        /* Main Grid */
        .main-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2rem;
        }

        /* Cards */
        .card {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card-header {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
            padding: 1.2rem 1.5rem;
        }

        .card-header h2 {
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-header.info {
            background: linear-gradient(135deg, #17a2b8, #138496);
        }

        .card-body {
            padding: 1.5rem;
        }

        /* User Info */
        .user-info {
            margin-bottom: 1.5rem;
        }

        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 0.8rem 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .info-row:last-child {
            border-bottom: none;
        }

        .info-label {
            font-weight: 600;
            color: #666;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .info-label i {
            color: #17a2b8;
            width: 20px;
        }

        .info-value {
            color: #333;
            font-weight: 500;
        }

        /* Document Preview */
        .doc-preview {
            text-align: center;
            margin-top: 1rem;
        }

        .doc-image {
            max-width: 100%;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            cursor: pointer;
        }

        .doc-pdf {
            background: #f8f9fa;
            padding: 2rem;
            border-radius: 10px;
            text-align: center;
        }

        .doc-pdf i {
            font-size: 4rem;
            color: #dc3545;
        }

        .view-btn {
            display: inline-block;
            margin-top: 1rem;
            padding: 0.5rem 1rem;
            background: #17a2b8;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            font-size: 0.85rem;
        }

        /* Form */
        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #333;
        }

        .form-group label i {
            color: #dc3545;
            margin-right: 5px;
        }

        .form-group textarea {
            width: 100%;
            padding: 0.8rem;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-family: 'Poppins', sans-serif;
            font-size: 0.9rem;
            resize: vertical;
            transition: all 0.3s;
        }

        .form-group textarea:focus {
            outline: none;
            border-color: #dc3545;
            box-shadow: 0 0 0 3px rgba(220,53,69,0.1);
        }

        /* Reason Suggestions */
        .reason-suggestions {
            margin-top: 1rem;
        }

        .suggestion-btn {
            display: inline-block;
            background: #f0f0f0;
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            font-size: 0.7rem;
            margin: 0.2rem;
            cursor: pointer;
            transition: all 0.3s;
        }

        .suggestion-btn:hover {
            background: #dc3545;
            color: white;
        }

        /* Alert Messages */
        .alert {
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 10px;
            animation: slideIn 0.3s ease-out;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Buttons */
        .btn-group {
            display: flex;
            gap: 1rem;
            margin-top: 1.5rem;
        }

        .btn {
            flex: 1;
            padding: 0.8rem;
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            text-decoration: none;
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(220,53,69,0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: white;
            border-radius: 15px;
            max-width: 90%;
            max-height: 90%;
            overflow: auto;
            position: relative;
        }

        .modal-header {
            padding: 1rem;
            background: #dc3545;
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-radius: 15px 15px 0 0;
        }

        .modal-body {
            padding: 1.5rem;
            text-align: center;
        }

        .modal-body img {
            max-width: 100%;
            max-height: 70vh;
        }

        .close-modal {
            background: none;
            border: none;
            color: white;
            font-size: 1.5rem;
            cursor: pointer;
        }

        /* Responsive */
        @media (max-width: 768px) {
            body {
                padding: 1rem;
            }

            .main-grid {
                grid-template-columns: 1fr;
            }

            .header {
                flex-direction: column;
                text-align: center;
            }

            .btn-group {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <!-- Header -->
    <div class="header">
        <h1>
            <i class="fas fa-times-circle"></i>
            Reject KYC Application
        </h1>
        <a href="dashboard.php" class="back-btn">
            <i class="fas fa-arrow-left"></i> Back to Dashboard
        </a>
    </div>

    <?php if($error): ?>
    <div class="alert alert-error">
        <i class="fas fa-exclamation-circle"></i>
        <span><?= $error ?></span>
    </div>
    <?php endif; ?>

    <div class="main-grid">
        <!-- User Information Card -->
        <div class="card">
            <div class="card-header info">
                <h2>
                    <i class="fas fa-user"></i>
                    Member Information
                </h2>
            </div>
            <div class="card-body">
                <div class="user-info">
                    <div class="info-row">
                        <span class="info-label"><i class="fas fa-id-card"></i> Member ID</span>
                        <span class="info-value">#<?= str_pad($user['id'], 6, '0', STR_PAD_LEFT) ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label"><i class="fas fa-user"></i> Full Name</span>
                        <span class="info-value"><?= htmlspecialchars($user['name']) ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label"><i class="fas fa-envelope"></i> Email Address</span>
                        <span class="info-value"><?= htmlspecialchars($user['email']) ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label"><i class="fas fa-phone"></i> Mobile Number</span>
                        <span class="info-value"><?= htmlspecialchars($user['mobile'] ?: 'Not provided') ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label"><i class="fas fa-calendar-alt"></i> Submitted On</span>
                        <span class="info-value"><?= date('d M Y, h:i A', strtotime($user['created_at'])) ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label"><i class="fas fa-id-card"></i> Current KYC Status</span>
                        <span class="info-value">
                            <span class="badge badge-pending" style="background: #fff3cd; color: #856404; padding: 0.2rem 0.8rem; border-radius: 20px;">
                                <?= ucfirst($user['kyc_status']) ?>
                            </span>
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- KYC Document Card -->
        <div class="card">
            <div class="card-header info">
                <h2>
                    <i class="fas fa-file-alt"></i>
                    KYC Document
                </h2>
            </div>
            <div class="card-body">
                <?php if($kyc_doc): ?>
                    <div class="doc-preview">
                        <?php if($kyc_doc['type'] == 'image'): ?>
                            <img src="<?= $kyc_doc['url'] ?>" alt="KYC Document" class="doc-image" onclick="showDocument('<?= $kyc_doc['url'] ?>')">
                            <br>
                            <button class="view-btn" onclick="showDocument('<?= $kyc_doc['url'] ?>')">
                                <i class="fas fa-search-plus"></i> View Full Image
                            </button>
                        <?php else: ?>
                            <div class="doc-pdf">
                                <i class="fas fa-file-pdf"></i>
                                <p>PDF Document</p>
                                <a href="<?= $kyc_doc['url'] ?>" target="_blank" class="view-btn">
                                    <i class="fas fa-file-pdf"></i> View PDF
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div style="text-align: center; padding: 2rem; color: #999;">
                        <i class="fas fa-times-circle" style="font-size: 3rem;"></i>
                        <p style="margin-top: 0.5rem;">No KYC document found</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Rejection Form Card -->
    <div class="card" style="margin-top: 2rem;">
        <div class="card-header">
            <h2>
                <i class="fas fa-ban"></i>
                Rejection Details
            </h2>
        </div>
        <div class="card-body">
            <form method="POST">
                <div class="form-group">
                    <label><i class="fas fa-comment"></i> Reason for Rejection</label>
                    <textarea name="rejection_reason" id="rejection_reason" rows="5" required 
                              placeholder="Please provide detailed reason why this KYC is being rejected..."></textarea>
                    
                    <div class="reason-suggestions">
                        <strong style="font-size: 0.7rem; color: #666;">Quick suggestions:</strong>
                        <span class="suggestion-btn" onclick="addSuggestion('Document is blurry or unreadable')">📷 Blurry document</span>
                        <span class="suggestion-btn" onclick="addSuggestion('Document is expired')">📅 Expired document</span>
                        <span class="suggestion-btn" onclick="addSuggestion('Document does not match user name')">👤 Name mismatch</span>
                        <span class="suggestion-btn" onclick="addSuggestion('Invalid document type')">📄 Invalid document type</span>
                        <span class="suggestion-btn" onclick="addSuggestion('Document is incomplete')">📑 Incomplete document</span>
                        <span class="suggestion-btn" onclick="addSuggestion('Unable to verify authenticity')">🔍 Unable to verify</span>
                    </div>
                </div>

                <div class="alert alert-error" style="background: #fff3cd; border-left-color: #ffc107; color: #856404;">
                    <i class="fas fa-exclamation-triangle"></i>
                    <span><strong>Warning:</strong> This action cannot be undone. The member will need to resubmit their KYC documents after rejection.</span>
                </div>

                <div class="btn-group">
                    <a href="dashboard.php" class="btn btn-secondary">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                    <button type="submit" class="btn btn-danger" onclick="return confirmRejection()">
                        <i class="fas fa-ban"></i> Confirm Rejection
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Document Modal -->
<div id="docModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>KYC Document</h3>
            <button class="close-modal" onclick="closeModal()">&times;</button>
        </div>
        <div class="modal-body">
            <img id="modalImage" src="" alt="KYC Document">
        </div>
    </div>
</div>

<script>
    function showDocument(url) {
        const modal = document.getElementById('docModal');
        const modalImage = document.getElementById('modalImage');
        modalImage.src = url;
        modal.style.display = 'flex';
    }

    function closeModal() {
        document.getElementById('docModal').style.display = 'none';
        document.getElementById('modalImage').src = '';
    }

    function addSuggestion(text) {
        const textarea = document.getElementById('rejection_reason');
        const currentValue = textarea.value;
        if (currentValue) {
            textarea.value = currentValue + '\n• ' + text;
        } else {
            textarea.value = '• ' + text;
        }
        textarea.focus();
    }

    function confirmRejection() {
        const reason = document.getElementById('rejection_reason').value.trim();
        if (!reason) {
            alert('Please provide a reason for rejection');
            return false;
        }
        return confirm('Are you sure you want to reject this KYC?\n\nReason: ' + reason + '\n\nThis action cannot be undone. The member will need to resubmit their documents.');
    }

    // Close modal on escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeModal();
        }
    });

    // Close modal on click outside
    window.onclick = function(event) {
        const modal = document.getElementById('docModal');
        if (event.target == modal) {
            closeModal();
        }
    }
</script>
</body>
</html>