<?php
session_start();
require_once "../config/db.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Include header
include "../includes/header.php";

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

// Check existing verification
$existing = mysqli_query($conn, "SELECT * FROM user_id_proofs WHERE user_id = '$user_id' ORDER BY id DESC LIMIT 1");
$has_proof = mysqli_num_rows($existing) > 0;
$proof_data = $has_proof ? mysqli_fetch_assoc($existing) : null;

// Handle form submission
if (isset($_POST['submit_id_proof'])) {
    $proof_type = mysqli_real_escape_string($conn, $_POST['proof_type']);
    $proof_number = mysqli_real_escape_string($conn, $_POST['proof_number']);
    $full_name = mysqli_real_escape_string($conn, $_POST['full_name']);
    $dob = mysqli_real_escape_string($conn, $_POST['date_of_birth']);
    
    // File upload
    if (isset($_FILES['front_image'])) {
        $file = $_FILES['front_image'];
        
        if ($file['error'] === 0) {
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $allowed = ['jpg', 'jpeg', 'png', 'pdf'];
            
            if (in_array(strtolower($ext), $allowed)) {
                if ($file['size'] <= 5 * 1024 * 1024) { // 5MB
                    $filename = 'front_' . time() . '_' . $user_id . '.' . $ext;
                    $upload_path = "../assets/images/id_proofs/" . $filename;
                    
                    if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                        // Insert into database
                        $query = "INSERT INTO user_id_proofs (user_id, proof_type, proof_number, full_name, date_of_birth, front_image, verification_status) 
                                  VALUES ('$user_id', '$proof_type', '$proof_number', '$full_name', '$dob', '$filename', 'pending')";
                        
                        if (mysqli_query($conn, $query)) {
                            $success = "ID proof submitted successfully!";
                            // Refresh data
                            $existing = mysqli_query($conn, "SELECT * FROM user_id_proofs WHERE user_id = '$user_id' ORDER BY id DESC LIMIT 1");
                            $has_proof = mysqli_num_rows($existing) > 0;
                            $proof_data = $has_proof ? mysqli_fetch_assoc($existing) : null;
                        } else {
                            $error = "Database error: " . mysqli_error($conn);
                        }
                    } else {
                        $error = "Failed to upload file.";
                    }
                } else {
                    $error = "File too large. Max 5MB allowed.";
                }
            } else {
                $error = "Invalid file type. Only JPG, PNG, PDF allowed.";
            }
        } else {
            $error = "Please select a file.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ID Verification</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background: #f8f9fa;
        }
        
        .verification-card {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-top: 20px;
        }
        
        .status-badge {
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: bold;
        }
        
        .pending { background: #fff3cd; color: #856404; }
        .verified { background: #d4edda; color: #155724; }
        .rejected { background: #f8d7da; color: #721c24; }
    </style>
</head>
<body>
    <!-- Simple Header -->
    <nav class="navbar navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-tshirt me-2"></i>ShopNest
            </a>
            <a href="profile.php" class="btn btn-light">Back to Profile</a>
        </div>
    </nav>
    
    <div class="container mt-4">
        <h2 class="mb-4"><i class="fas fa-id-card me-2"></i>ID Verification</h2>
        
        <?php if($error): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <?php if($success): ?>
            <div class="alert alert-success"><?php echo $success; ?></div>
        <?php endif; ?>
        
        <!-- Current Status -->
        <?php if($has_proof): ?>
        <div class="verification-card mb-4">
            <h4>Current Status</h4>
            <p><strong>Document Type:</strong> <?php echo ucfirst($proof_data['proof_type']); ?></p>
            <p><strong>Document Number:</strong> <?php echo htmlspecialchars($proof_data['proof_number']); ?></p>
            <p><strong>Status:</strong> 
                <span class="status-badge <?php echo $proof_data['verification_status']; ?>">
                    <?php echo ucfirst($proof_data['verification_status']); ?>
                </span>
            </p>
            
            <?php if($proof_data['verification_status'] == 'rejected'): ?>
                <p><strong>Reason:</strong> <?php echo htmlspecialchars($proof_data['rejection_reason']); ?></p>
                <p class="text-danger">Please submit again with correct information.</p>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <!-- Submit Form (only if no proof or rejected) -->
        <?php if(!$has_proof || $proof_data['verification_status'] == 'rejected'): ?>
        <div class="verification-card">
            <h4>Submit ID Proof</h4>
            <p class="text-muted mb-4">Upload a clear image of your government ID</p>
            
            <form method="POST" enctype="multipart/form-data">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>ID Type</label>
                        <select name="proof_type" class="form-control" required>
                            <option value="">Select Document</option>
                            <option value="aadhar">Aadhar Card</option>
                            <option value="passport">Passport</option>
                            <option value="driving_license">Driving License</option>
                            <option value="pan_card">PAN Card</option>
                        </select>
                    </div>
                    
                    <div class="col-md-6 mb-3">
                        <label>Document Number</label>
                        <input type="text" name="proof_number" class="form-control" required>
                    </div>
                    
                    <div class="col-md-6 mb-3">
                        <label>Full Name (as on document)</label>
                        <input type="text" name="full_name" class="form-control" required>
                    </div>
                    
                    <div class="col-md-6 mb-3">
                        <label>Date of Birth</label>
                        <input type="date" name="date_of_birth" class="form-control" required>
                    </div>
                    
                    <div class="col-md-12 mb-3">
                        <label>Front Side Image (Required)</label>
                        <input type="file" name="front_image" class="form-control" accept=".jpg,.jpeg,.png,.pdf" required>
                        <small class="text-muted">Max 5MB. JPG, PNG, PDF only.</small>
                    </div>
                </div>
                
                <button type="submit" name="submit_id_proof" class="btn btn-primary">
                    <i class="fas fa-upload me-2"></i>Submit for Verification
                </button>
                <a href="profile.php" class="btn btn-secondary">Cancel</a>
            </form>
        </div>
        <?php endif; ?>
    </div>
    
    <?php include "../includes/footer.php"; ?>
</body>
</html>