<?php session_start();

include 'includes/head.php';



// Get user data
$user_sql = "SELECT * FROM users WHERE id = '$user_id'";
$user_result = mysqli_query($conn, $user_sql);
$user_data = mysqli_fetch_assoc($user_result);

// Get user's KYC documents
$kyc_sql = "SELECT * FROM kyc_documents WHERE user_id = '$user_id' ORDER BY upload_date DESC";
$kyc_result = mysqli_query($conn, $kyc_sql);

// Initialize variables
$personal_success = $personal_error = $employment_success = $employment_error = '';
$password_success = $password_error = $notification_success = $notification_error = '';
$kyc_success = $kyc_error = '';

// Handle form submissions
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['update_personal'])) {
        // Update personal information
        $first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
        $last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
        $phone = mysqli_real_escape_string($conn, $_POST['phone']);
        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $date_of_birth = mysqli_real_escape_string($conn, $_POST['date_of_birth']);
        $address = mysqli_real_escape_string($conn, $_POST['address']);
        $city = mysqli_real_escape_string($conn, $_POST['city']);
        $province = mysqli_real_escape_string($conn, $_POST['province']);
        $postal_code = mysqli_real_escape_string($conn, $_POST['postal_code']);
        
        $update_sql = "UPDATE users SET 
                      first_name = '$first_name',
                      last_name = '$last_name',
                      phone = '$phone',
                      email = '$email',
                      date_of_birth = '$date_of_birth',
                      address = '$address',
                      city = '$city',
                      province = '$province',
                      postal_code = '$postal_code'
                      WHERE id = '$user_id'";
        
        if (mysqli_query($conn, $update_sql)) {
            $personal_success = "Personal information updated successfully!";
            // Refresh user data
            $user_result = mysqli_query($conn, $user_sql);
            $user_data = mysqli_fetch_assoc($user_result);
        } else {
            $personal_error = "Update failed: " . mysqli_error($conn);
        }
    }
    
    if (isset($_POST['update_employment'])) {
        // Update employment details
        $employment_status = mysqli_real_escape_string($conn, $_POST['employment_status']);
        $monthly_income = mysqli_real_escape_string($conn, $_POST['monthly_income']);
        $employer_name = isset($_POST['employer_name']) ? mysqli_real_escape_string($conn, $_POST['employer_name']) : '';
        $job_title = isset($_POST['job_title']) ? mysqli_real_escape_string($conn, $_POST['job_title']) : '';
        $employment_duration = isset($_POST['employment_duration']) ? mysqli_real_escape_string($conn, $_POST['employment_duration']) : '';
        
        $update_sql = "UPDATE users SET 
                      employment_status = '$employment_status',
                      monthly_income = '$monthly_income'";
        
        // Add optional fields if they exist in the database
        if (isset($user_data['employer_name'])) {
            $update_sql .= ", employer_name = '$employer_name'";
        }
        if (isset($user_data['job_title'])) {
            $update_sql .= ", job_title = '$job_title'";
        }
        if (isset($user_data['employment_duration'])) {
            $update_sql .= ", employment_duration = '$employment_duration'";
        }
        
        $update_sql .= " WHERE id = '$user_id'";
        
        if (mysqli_query($conn, $update_sql)) {
            $employment_success = "Employment details updated successfully!";
            $user_result = mysqli_query($conn, $user_sql);
            $user_data = mysqli_fetch_assoc($user_result);
        } else {
            $employment_error = "Update failed: " . mysqli_error($conn);
        }
    }
    
    if (isset($_POST['change_password'])) {
        // Change password
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];
        
        // Check if password_verify function exists (PHP 5.5+)
        if (function_exists('password_verify')) {
            $password_valid = password_verify($current_password, $user_data['password']);
        } else {
            // Fallback for older PHP versions - NOT SECURE for production
            $password_valid = (md5($current_password) === $user_data['password']);
        }
        
        if ($password_valid) {
            if ($new_password === $confirm_password) {
                if (strlen($new_password) >= 6) {
                    // Use password_hash if available, otherwise use md5 (not secure)
                    if (function_exists('password_hash')) {
                        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                    } else {
                        $hashed_password = md5($new_password); // Not secure for production
                    }
                    
                    $update_sql = "UPDATE users SET password = '$hashed_password' WHERE id = '$user_id'";
                    
                    if (mysqli_query($conn, $update_sql)) {
                        $password_success = "Password changed successfully!";
                    } else {
                        $password_error = "Password change failed: " . mysqli_error($conn);
                    }
                } else {
                    $password_error = "Password must be at least 6 characters long";
                }
            } else {
                $password_error = "New passwords do not match";
            }
        } else {
            $password_error = "Current password is incorrect";
        }
    }
    
    if (isset($_POST['update_notifications'])) {
        // Update notification preferences
        $email_notifications = isset($_POST['email_notifications']) ? 1 : 0;
        $sms_notifications = isset($_POST['sms_notifications']) ? 1 : 0;
        $push_notifications = isset($_POST['push_notifications']) ? 1 : 0;
        $marketing_emails = isset($_POST['marketing_emails']) ? 1 : 0;
        
        // Build update query only for fields that exist
        $update_sql = "UPDATE users SET";
        $updates = array();
        
        if (isset($user_data['email_notifications'])) {
            $updates[] = " email_notifications = '$email_notifications'";
        }
        if (isset($user_data['sms_notifications'])) {
            $updates[] = " sms_notifications = '$sms_notifications'";
        }
        if (isset($user_data['push_notifications'])) {
            $updates[] = " push_notifications = '$push_notifications'";
        }
        if (isset($user_data['marketing_emails'])) {
            $updates[] = " marketing_emails = '$marketing_emails'";
        }
        
        if (!empty($updates)) {
            $update_sql .= implode(',', $updates) . " WHERE id = '$user_id'";
            
            if (mysqli_query($conn, $update_sql)) {
                $notification_success = "Notification preferences updated successfully!";
                $user_result = mysqli_query($conn, $user_sql);
                $user_data = mysqli_fetch_assoc($user_result);
            } else {
                $notification_error = "Update failed: " . mysqli_error($conn);
            }
        }
    }
    
    if (isset($_FILES['kyc_document'])) {
        // Handle KYC document upload
        $document_type = mysqli_real_escape_string($conn, $_POST['document_type']);
        $upload_result = handleKYCDocumentUpload($user_id, $document_type);
        
        if ($upload_result['success']) {
            $kyc_success = "Document uploaded successfully!";
            // Refresh KYC documents
            $kyc_result = mysqli_query($conn, $kyc_sql);
        } else {
            $kyc_error = $upload_result['error'];
        }
    }
}

function handleKYCDocumentUpload($user_id, $document_type) {
    global $conn;
    
    $upload_dir = "uploads/kyc_documents/" . $user_id . "/";
    
    // Create directory if it doesn't exist
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    $allowed_types = array('jpg', 'jpeg', 'png', 'pdf');
    $max_size = 5 * 1024 * 1024; // 5MB
    
    if (isset($_FILES['kyc_document']) && $_FILES['kyc_document']['error'] == 0) {
        $file = $_FILES['kyc_document'];
        $file_info = pathinfo($file['name']);
        $extension = strtolower($file_info['extension']);
        
        if (in_array($extension, $allowed_types) && $file['size'] <= $max_size) {
            $filename = $document_type . "_" . time() . "." . $extension;
            $filepath = $upload_dir . $filename;
            
            if (move_uploaded_file($file['tmp_name'], $filepath)) {
                // Check if document already exists
                $check_sql = "SELECT id FROM kyc_documents WHERE user_id = '$user_id' AND document_type = '$document_type'";
                $check_result = mysqli_query($conn, $check_sql);
                
                if (mysqli_num_rows($check_result) > 0) {
                    // Update existing
                    $sql = "UPDATE kyc_documents SET document_path = '$filepath', upload_date = NOW() 
                           WHERE user_id = '$user_id' AND document_type = '$document_type'";
                } else {
                    // Insert new
                    $sql = "INSERT INTO kyc_documents (user_id, document_type, document_path) 
                           VALUES ('$user_id', '$document_type', '$filepath')";
                }
                
                if (mysqli_query($conn, $sql)) {
                    return array('success' => true, 'filepath' => $filepath);
                }
            }
        } else {
            return array('success' => false, 'error' => 'Invalid file type or size (max 5MB)');
        }
    }
    
    return array('success' => false, 'error' => 'File upload failed');
}

// Get default values for optional fields
$employer_name = isset($user_data['employer_name']) ? $user_data['employer_name'] : '';
$job_title = isset($user_data['job_title']) ? $user_data['job_title'] : '';
$employment_duration = isset($user_data['employment_duration']) ? $user_data['employment_duration'] : '';
$email_notifications = isset($user_data['email_notifications']) ? $user_data['email_notifications'] : 1;
$sms_notifications = isset($user_data['sms_notifications']) ? $user_data['sms_notifications'] : 1;
$push_notifications = isset($user_data['push_notifications']) ? $user_data['push_notifications'] : 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile & Settings - E-Finance Loans</title>
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
    .profile-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px;
        padding: 30px;
        margin-bottom: 30px;
    }
    .verification-badge {
        font-size: 0.9em;
        padding: 8px 15px;
    }
    .document-upload-area {
        border: 2px dashed #ddd;
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        transition: all 0.3s ease;
        background: #121212ff;
    }
    .document-upload-area:hover {
        border-color: #4CAF50;
        background: #e8f5e8;
    }
    .nav-pills .nav-link.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
    }
    .security-level {
        height: 8px;
        border-radius: 4px;
    }
    .document-status {
        font-size: 0.8em;
        padding: 4px 8px;
    }
    </style>
</head>
<body class="dashboard">
    <div id="main-wrapper">
        
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>

        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <!-- Profile Header -->
                        <div class="profile-header">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h2 class="mb-1"><?php echo htmlspecialchars($user_data['first_name'] . ' ' . $user_data['last_name']); ?></h2>
                                    <p class="mb-2">Welcome to your profile settings</p>
                                    <div class="d-flex align-items-center gap-3">
                                        <span class="badge <?php echo $user_data['verification_completed'] ? 'bg-success' : 'bg-warning'; ?> verification-badge">
                                            <?php echo $user_data['verification_completed'] ? '✓ Verified' : '⏳ Verification Pending'; ?>
                                        </span>
                                        <span class="small">Member since <?php echo date('M Y', strtotime($user_data['registration_date'])); ?></span>
                                    </div>
                                </div>
                                <div class="col-md-4 text-end">
                                    <div class="bg-white bg-opacity-25 rounded-circle d-inline-flex align-items-center justify-content-center" 
                                         style="width: 80px; height: 80px;">
                                        <i class="fi fi-rr-user fs-2 text-white"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <!-- Left Navigation -->
                    <div class="col-xl-3">
                        <div class="card">
                            <div class="card-body p-0">
                                <ul class="nav nav-pills flex-column gap-2 p-3">
                                    <li class="nav-item">
                                        <a class="nav-link active" data-bs-toggle="pill" href="#personal">
                                            <i class="fi fi-rr-user me-2"></i>Personal Info
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" data-bs-toggle="pill" href="#security">
                                            <i class="fi fi-rr-lock me-2"></i>Password & Security
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" data-bs-toggle="pill" href="#notifications">
                                            <i class="fi fi-rr-bell me-2"></i>Notifications
                                        </a>
                                    </li>
                                    <li class="nav-item mt-4">
                                        <a href="logout.php" class="nav-link text-danger">
                                            <i class="fi fi-bs-sign-out-alt me-2"></i>Logout
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </div>

                        <!-- Security Status -->
                        <div class="card mt-4">
                            <div class="card-body">
                                <h6 class="card-title">Security Status</h6>
                                <div class="mb-3">
                                    <div class="d-flex justify-content-between mb-1">
                                        <small>Profile Strength</small>
                                        <small><?php echo $user_data['verification_completed'] ? 'Strong' : 'Medium'; ?></small>
                                    </div>
                                    <div class="progress security-level">
                                        <div class="progress-bar bg-<?php echo $user_data['verification_completed'] ? 'success' : 'warning'; ?>" 
                                             style="width: <?php echo $user_data['verification_completed'] ? '85' : '60'; ?>%"></div>
                                    </div>
                                </div>
                                <div class="small text-muted">
                                    <div class="d-flex align-items-center mb-1">
                                        <i class="fi fi-rr-check text-success me-2"></i>
                                        <span>Email Verified</span>
                                    </div>
                                    <div class="d-flex align-items-center mb-1">
                                        <i class="fi fi-rr-<?php echo $user_data['verification_completed'] ? 'check text-success' : 'clock text-warning'; ?> me-2"></i>
                                        <span>KYC <?php echo $user_data['verification_completed'] ? 'Verified' : 'Pending'; ?></span>
                                    </div>
                                    <div class="d-flex align-items-center">
                                        <i class="fi fi-rr-phone-call text-success me-2"></i>
                                        <span>Phone Verified</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Right Content -->
                    <div class="col-xl-9">
                        <div class="tab-content">
                            <!-- Personal Information Tab -->
                            <div class="tab-pane fade show active" id="personal">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="fi fi-rr-user me-2"></i>Personal Information
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <?php if(!empty($personal_success)): ?>
                                            <div class="alert alert-success"><?php echo $personal_success; ?></div>
                                        <?php endif; ?>
                                        <?php if(!empty($personal_error)): ?>
                                            <div class="alert alert-danger"><?php echo $personal_error; ?></div>
                                        <?php endif; ?>

                                        <form method="POST">
                                            <div class="row g-3">
                                                <div class="col-md-6">
                                                    <label class="form-label">First Name</label>
                                                    <input type="text" class="form-control" name="first_name" 
                                                           value="<?php echo htmlspecialchars($user_data['first_name']); ?>" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Last Name</label>
                                                    <input type="text" class="form-control" name="last_name" 
                                                           value="<?php echo htmlspecialchars($user_data['last_name']); ?>" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Email Address</label>
                                                    <input type="email" class="form-control" name="email" 
                                                           value="<?php echo htmlspecialchars($user_data['email']); ?>" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Phone Number</label>
                                                    <input type="tel" class="form-control" name="phone" 
                                                           value="<?php echo htmlspecialchars($user_data['phone']); ?>" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Date of Birth</label>
                                                    <input type="date" class="form-control" name="date_of_birth" 
                                                           value="<?php echo $user_data['date_of_birth']; ?>" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">ID Number</label>
                                                    <input type="text" class="form-control" value="<?php echo $user_data['id_number']; ?>" readonly>
                                                    <small class="text-muted">ID number cannot be changed</small>
                                                </div>
                                                <div class="col-12">
                                                    <label class="form-label">Address</label>
                                                    <input type="text" class="form-control" name="address" 
                                                           value="<?php echo htmlspecialchars($user_data['address']); ?>" required>
                                                </div>
                                                <div class="col-md-4">
                                                    <label class="form-label">City</label>
                                                    <input type="text" class="form-control" name="city" 
                                                           value="<?php echo htmlspecialchars($user_data['city']); ?>" required>
                                                </div>
                                                <div class="col-md-4">
                                                    <label class="form-label">Province</label>
                                                    <select class="form-select" name="province" required>
                                                        <option value="Gauteng" <?php echo $user_data['province'] == 'Gauteng' ? 'selected' : ''; ?>>Gauteng</option>
                                                        <option value="Western Cape" <?php echo $user_data['province'] == 'Western Cape' ? 'selected' : ''; ?>>Western Cape</option>
                                                        <option value="KwaZulu-Natal" <?php echo $user_data['province'] == 'KwaZulu-Natal' ? 'selected' : ''; ?>>KwaZulu-Natal</option>
                                                        <option value="Eastern Cape" <?php echo $user_data['province'] == 'Eastern Cape' ? 'selected' : ''; ?>>Eastern Cape</option>
                                                        <option value="Free State" <?php echo $user_data['province'] == 'Free State' ? 'selected' : ''; ?>>Free State</option>
                                                        <option value="Limpopo" <?php echo $user_data['province'] == 'Limpopo' ? 'selected' : ''; ?>>Limpopo</option>
                                                        <option value="Mpumalanga" <?php echo $user_data['province'] == 'Mpumalanga' ? 'selected' : ''; ?>>Mpumalanga</option>
                                                        <option value="North West" <?php echo $user_data['province'] == 'North West' ? 'selected' : ''; ?>>North West</option>
                                                        <option value="Northern Cape" <?php echo $user_data['province'] == 'Northern Cape' ? 'selected' : ''; ?>>Northern Cape</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-4">
                                                    <label class="form-label">Postal Code</label>
                                                    <input type="text" class="form-control" name="postal_code" 
                                                           value="<?php echo htmlspecialchars($user_data['postal_code']); ?>" required>
                                                </div>
                                            </div>
                                            <div class="mt-4">
                                                <button type="submit" name="update_personal" class="btn btn-primary">Update Personal Information</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>

                            <!-- Employment Details Tab -->
                            <div class="tab-pane fade" id="employment">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="fi fi-rr-briefcase me-2"></i>Employment & Income Details
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <?php if(!empty($employment_success)): ?>
                                            <div class="alert alert-success"><?php echo $employment_success; ?></div>
                                        <?php endif; ?>
                                        <?php if(!empty($employment_error)): ?>
                                            <div class="alert alert-danger"><?php echo $employment_error; ?></div>
                                        <?php endif; ?>

                                        <form method="POST">
                                            <div class="row g-3">
                                                <div class="col-md-6">
                                                    <label class="form-label">Employment Status</label>
                                                    <select class="form-select" name="employment_status" required>
                                                        <option value="">Select status</option>
                                                        <option value="Employed" <?php echo $user_data['employment_status'] == 'Employed' ? 'selected' : ''; ?>>Employed</option>
                                                        <option value="Self-Employed" <?php echo $user_data['employment_status'] == 'Self-Employed' ? 'selected' : ''; ?>>Self-Employed</option>
                                                        <option value="Student" <?php echo $user_data['employment_status'] == 'Student' ? 'selected' : ''; ?>>Student</option>
                                                        <option value="Retired" <?php echo $user_data['employment_status'] == 'Retired' ? 'selected' : ''; ?>>Retired</option>
                                                        <option value="Unemployed" <?php echo $user_data['employment_status'] == 'Unemployed' ? 'selected' : ''; ?>>Unemployed</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Monthly Income (R)</label>
                                                    <input type="number" class="form-control" name="monthly_income" 
                                                           value="<?php echo $user_data['monthly_income']; ?>" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Employer Name</label>
                                                    <input type="text" class="form-control" name="employer_name" 
                                                           value="<?php echo htmlspecialchars($employer_name); ?>">
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Job Title</label>
                                                    <input type="text" class="form-control" name="job_title" 
                                                           value="<?php echo htmlspecialchars($job_title); ?>">
                                                </div>
                                                <div class="col-12">
                                                    <label class="form-label">Employment Duration</label>
                                                    <select class="form-select" name="employment_duration">
                                                        <option value="">Select duration</option>
                                                        <option value="Less than 1 year" <?php echo $employment_duration == 'Less than 1 year' ? 'selected' : ''; ?>>Less than 1 year</option>
                                                        <option value="1-3 years" <?php echo $employment_duration == '1-3 years' ? 'selected' : ''; ?>>1-3 years</option>
                                                        <option value="3-5 years" <?php echo $employment_duration == '3-5 years' ? 'selected' : ''; ?>>3-5 years</option>
                                                        <option value="5+ years" <?php echo $employment_duration == '5+ years' ? 'selected' : ''; ?>>5+ years</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="mt-4">
                                                <button type="submit" name="update_employment" class="btn btn-primary">Update Employment Details</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>

                            <!-- KYC Verification Tab -->
                            <div class="tab-pane fade" id="kyc">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="fi fi-rr-id-card-clip me-2"></i>KYC Verification
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <?php if(!empty($kyc_success)): ?>
                                            <div class="alert alert-success"><?php echo $kyc_success; ?></div>
                                        <?php endif; ?>
                                        <?php if(!empty($kyc_error)): ?>
                                            <div class="alert alert-danger"><?php echo $kyc_error; ?></div>
                                        <?php endif; ?>

                                        <!-- KYC Status -->
                                        <div class="row mb-4">
                                            <div class="col-12">
                                                <div class="card bg-dark">
                                                    <div class="card-body">
                                                        <div class="row align-items-center">
                                                            <div class="col-md-8">
                                                                <h6 class="mb-1">Verification Status</h6>
                                                                <p class="mb-0 text-muted">
                                                                    <?php if ($user_data['verification_completed']): ?>
                                                                        ✅ Your account has been verified and you can apply for loans
                                                                    <?php else: ?>
                                                                        ⏳ Your verification is pending. Please upload the required documents.
                                                                    <?php endif; ?>
                                                                </p>
                                                            </div>
                                                            <div class="col-md-4 text-end">
                                                                <span class="badge <?php echo $user_data['verification_completed'] ? 'bg-success' : 'bg-warning'; ?>">
                                                                    <?php echo $user_data['verification_completed'] ? 'Verified' : 'Pending'; ?>
                                                                </span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Document Upload -->
                                        <div class="row g-4">
                                            <!-- ID Document -->
                                            <div class="col-md-6">
                                                <div class="document-upload-area">
                                                    <i class="fi fi-rr-id-card-clip fs-1 text-primary mb-3"></i>
                                                    <h6>ID Document</h6>
                                                    <p class="text-muted small">Upload clear copy of your SA ID (Front & Back)</p>
                                                    <form method="POST" enctype="multipart/form-data">
                                                        <input type="hidden" name="document_type" value="id_document">
                                                        <input type="file" class="form-control mb-2" name="kyc_document" 
                                                               accept=".jpg,.jpeg,.png,.pdf" required>
                                                        <button type="submit" class="btn btn-primary btn-sm">Upload ID</button>
                                                    </form>
                                                </div>
                                            </div>

                                            <!-- Proof of Address -->
                                            <div class="col-md-6">
                                                <div class="document-upload-area">
                                                    <i class="fi fi-rr-marker fs-1 text-success mb-3"></i>
                                                    <h6>Proof of Address</h6>
                                                    <p class="text-muted small">Utility bill or bank statement (not older than 3 months)</p>
                                                    <form method="POST" enctype="multipart/form-data">
                                                        <input type="hidden" name="document_type" value="proof_of_address">
                                                        <input type="file" class="form-control mb-2" name="kyc_document" 
                                                               accept=".jpg,.jpeg,.png,.pdf" required>
                                                        <button type="submit" class="btn btn-success btn-sm">Upload Proof</button>
                                                    </form>
                                                </div>
                                            </div>

                                            <!-- Selfie -->
                                            <div class="col-md-6">
                                                <div class="document-upload-area">
                                                    <i class="fi fi-rr-camera fs-1 text-info mb-3"></i>
                                                    <h6>Selfie with ID</h6>
                                                    <p class="text-muted small">Clear selfie holding your ID document</p>
                                                    <form method="POST" enctype="multipart/form-data">
                                                        <input type="hidden" name="document_type" value="selfie_with_id">
                                                        <input type="file" class="form-control mb-2" name="kyc_document" 
                                                               accept=".jpg,.jpeg,.png" required>
                                                        <button type="submit" class="btn btn-info btn-sm">Upload Selfie</button>
                                                    </form>
                                                </div>
                                            </div>

                                            <!-- Proof of Income -->
                                            <div class="col-md-6">
                                                <div class="document-upload-area">
                                                    <i class="fi fi-rr-document fs-1 text-warning mb-3"></i>
                                                    <h6>Proof of Income</h6>
                                                    <p class="text-muted small">Latest payslip or 3 months bank statements</p>
                                                    <form method="POST" enctype="multipart/form-data">
                                                        <input type="hidden" name="document_type" value="proof_of_income">
                                                        <input type="file" class="form-control mb-2" name="kyc_document" 
                                                               accept=".jpg,.jpeg,.png,.pdf" required>
                                                        <button type="submit" class="btn btn-warning btn-sm">Upload Proof</button>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Uploaded Documents -->
                                        <div class="mt-5">
                                            <h6>Uploaded Documents</h6>
                                            <div class="table-responsive">
                                                <table class="table table-sm">
                                                    <thead>
                                                        <tr>
                                                            <th>Document Type</th>
                                                            <th>Upload Date</th>
                                                            <th>Status</th>
                                                            <th>Action</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php if(mysqli_num_rows($kyc_result) > 0): ?>
                                                            <?php while($doc = mysqli_fetch_assoc($kyc_result)): ?>
                                                            <tr>
                                                                <td><?php echo ucfirst(str_replace('_', ' ', $doc['document_type'])); ?></td>
                                                                <td><?php echo date('M j, Y', strtotime($doc['upload_date'])); ?></td>
                                                                <td>
                                                                    <span class="badge bg-<?php 
                                                                        echo $doc['verification_status'] == 'verified' ? 'success' : 
                                                                             ($doc['verification_status'] == 'rejected' ? 'danger' : 'warning'); 
                                                                    ?> document-status">
                                                                        <?php echo ucfirst($doc['verification_status']); ?>
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <?php if(file_exists($doc['document_path'])): ?>
                                                                        <a href="<?php echo $doc['document_path']; ?>" target="_blank" class="btn btn-sm btn-outline-primary">View</a>
                                                                    <?php else: ?>
                                                                        <span class="text-muted">File missing</span>
                                                                    <?php endif; ?>
                                                                </td>
                                                            </tr>
                                                            <?php endwhile; ?>
                                                        <?php else: ?>
                                                            <tr>
                                                                <td colspan="4" class="text-center text-muted">No documents uploaded yet</td>
                                                            </tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Password & Security Tab -->
                            <div class="tab-pane fade" id="security">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="fi fi-rr-lock me-2"></i>Password & Security
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <?php if(!empty($password_success)): ?>
                                            <div class="alert alert-success"><?php echo $password_success; ?></div>
                                        <?php endif; ?>
                                        <?php if(!empty($password_error)): ?>
                                            <div class="alert alert-danger"><?php echo $password_error; ?></div>
                                        <?php endif; ?>

                                        <form method="POST">
                                            <div class="row g-3">
                                                <div class="col-12">
                                                    <label class="form-label">Current Password</label>
                                                    <input type="password" class="form-control" name="current_password" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">New Password</label>
                                                    <input type="password" class="form-control" name="new_password" required>
                                                    <small class="text-muted">Minimum 6 characters</small>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Confirm New Password</label>
                                                    <input type="password" class="form-control" name="confirm_password" required>
                                                </div>
                                            </div>
                                            <div class="mt-4">
                                                <button type="submit" name="change_password" class="btn btn-primary">Change Password</button>
                                            </div>
                                        </form>

                                        <!-- Security Tips -->
                                        <div class="mt-5">
                                            <h6>Security Tips</h6>
                                            <ul class="small text-muted">
                                                <li>Use a strong password with letters, numbers, and symbols</li>
                                                <li>Never share your password with anyone</li>
                                                <li>Change your password regularly</li>
                                                <li>Use different passwords for different accounts</li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Notifications Tab -->
                            <div class="tab-pane fade" id="notifications">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="fi fi-rr-bell me-2"></i>Notification Preferences
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <?php if(!empty($notification_success)): ?>
                                            <div class="alert alert-success"><?php echo $notification_success; ?></div>
                                        <?php endif; ?>
                                        <?php if(!empty($notification_error)): ?>
                                            <div class="alert alert-danger"><?php echo $notification_error; ?></div>
                                        <?php endif; ?>

                                        <form method="POST">
                                            <div class="mb-4">
                                                <h6>Communication Channels</h6>
                                                <div class="form-check form-switch mb-3">
                                                    <input class="form-check-input" type="checkbox" name="email_notifications" 
                                                           id="email_notifications" <?php echo $email_notifications ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="email_notifications">
                                                        Email Notifications
                                                    </label>
                                                    <small class="text-muted d-block">Receive important updates via email</small>
                                                </div>
                                                <div class="form-check form-switch mb-3">
                                                    <input class="form-check-input" type="checkbox" name="sms_notifications" 
                                                           id="sms_notifications" <?php echo $sms_notifications ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="sms_notifications">
                                                        SMS Notifications
                                                    </label>
                                                    <small class="text-muted d-block">Get SMS alerts for payments and updates</small>
                                                </div>
                                                <div class="form-check form-switch mb-3">
                                                    <input class="form-check-input" type="checkbox" name="push_notifications" 
                                                           id="push_notifications" <?php echo $push_notifications ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="push_notifications">
                                                        Push Notifications
                                                    </label>
                                                    <small class="text-muted d-block">In-app notifications</small>
                                                </div>
                                            </div>

                                            <div class="mt-4">
                                                <button type="submit" name="update_notifications" class="btn btn-primary">Save Preferences</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include('includes/footer.php');?>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php mysqli_close($conn); ?>