<?php
require 'element/connection.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check multiple possible session variable names
$user_id = $_SESSION['user_id'];

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
} elseif (isset($_SESSION['userId'])) {
    $user_id = $_SESSION['userId'];
} elseif (isset($_SESSION['id'])) {
    $user_id = $_SESSION['id'];
} elseif (isset($_SESSION['uid'])) {
    $user_id = $_SESSION['uid'];
} else {
    // For testing only - REMOVE IN PRODUCTION
    $user_id = $_SESSION['user_id']; // Default top user ID
}

$userId = $user_id; // for compatibility

// Fetch user info - try multiple methods
$user = null;
$details = null;

// Method 1: Try with user_id column
$sql = "SELECT * FROM users WHERE user_id = $user_id";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    $user = $result->fetch_assoc();
    $details = $user;
} else {
    // Method 2: Try with id column
    $sql2 = "SELECT * FROM users WHERE id = $user_id";
    $result2 = $conn->query($sql2);
    if ($result2 && $result2->num_rows > 0) {
        $user = $result2->fetch_assoc();
        $user_id = $user['user_id'];
        $_SESSION['user_id'] = $user_id;
        $details = $user;
    } else {
        // Method 3: Get the first user (top user) as fallback
        $sql3 = "SELECT * FROM users ORDER BY id ASC LIMIT 1";
        $result3 = $conn->query($sql3);
        if ($result3 && $result3->num_rows > 0) {
            $user = $result3->fetch_assoc();
            $user_id = $user['user_id'];
            $_SESSION['user_id'] = $user_id;
            $details = $user;
        } else {
            die("No users found in database. Please contact support.");
        }
    }
}

$my_id = $_SESSION['user_id'];
$image = $details['image'] ?? 'default-avatar.png';

// Handle profile image upload
// Handle profile image upload
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["image"]["name"]) && $_FILES["image"]["name"] != '') {
    $id = $user_id; // Use $user_id, not $userId
    
    $imageName = $_FILES["image"]["name"];
    $imageSize = $_FILES["image"]["size"];
    $tmpName = $_FILES["image"]["tmp_name"];

    $validImageExtension = ['jpg', 'jpeg', 'png'];
    $imageExtension = strtolower(pathinfo($imageName, PATHINFO_EXTENSION));

    if (!in_array($imageExtension, $validImageExtension)) {
        echo "<script>alert('Invalid Image Extension'); window.location.href = 'profile.php';</script>";
    } elseif ($imageSize > 2000000) { // 2MB max
        echo "<script>alert('Image Size Is Too Large (max 2MB)'); window.location.href = 'profile.php';</script>";
    } else {
        // Create profile-img directory if not exists
        if (!file_exists('profile-img')) {
            mkdir('profile-img', 0777, true);
        }
        
        $newImageName = "profile_" . $id . "_" . date("Ymd_His") . "." . $imageExtension;
        
        if (move_uploaded_file($tmpName, 'profile-img/' . $newImageName)) {
            // Delete old image if not default
            if ($image != 'default-avatar.png' && file_exists('profile-img/' . $image)) {
                unlink('profile-img/' . $image);
            }
            
            $query = "UPDATE users SET image = '$newImageName' WHERE user_id = $id";
            mysqli_query($conn, $query);
            
            echo "<script>window.location.href = 'profile.php';</script>";
        } else {
            echo "<script>alert('Failed to upload image'); window.location.href = 'profile.php';</script>";
        }
    }
}

// Handle profile update
if (isset($_POST['profile_update_basic'])) {
    $name = mysqli_real_escape_string($conn, $_POST['agent_name']);
    $dob = mysqli_real_escape_string($conn, $_POST['dob']);
    $gender = mysqli_real_escape_string($conn, $_POST['gender']);
    $address = mysqli_real_escape_string($conn, $_POST['address']);
    $pan_no = strtoupper(mysqli_real_escape_string($conn, $_POST['pan_no']));
    $aadhar_no = mysqli_real_escape_string($conn, $_POST['aadhar_no']);
    $mobile = mysqli_real_escape_string($conn, $_POST['mob']);
    
    // Validate mobile
    if (!empty($mobile) && !preg_match('/^[0-9]{10}$/', $mobile)) {
        echo "<script>alert('Invalid mobile number! Must be 10 digits'); window.location.href = 'profile.php';</script>";
        exit();
    }
    
    $update_query = "UPDATE users SET 
        name = '$name',
        dob = '$dob',
        gender = '$gender',
        address = '$address',
        panno = '$pan_no',
        aadharno = '$aadhar_no',
        mobile = '$mobile'
        WHERE user_id = $user_id";
    
    if (mysqli_query($conn, $update_query)) {
        echo "<script>alert('Profile updated successfully!'); window.location.href = 'profile.php';</script>";
    } else {
        echo "<script>alert('Error updating profile: " . mysqli_error($conn) . "'); window.location.href = 'profile.php';</script>";
    }
}

// Handle bank details update
if (isset($_POST['profile_update_bank'])) {
    $bank_name = mysqli_real_escape_string($conn, $_POST['bank_name']);
    $account_holder = mysqli_real_escape_string($conn, $_POST['account_holder']);
    $account_number = mysqli_real_escape_string($conn, $_POST['account_number']);
    $confirm_account = mysqli_real_escape_string($conn, $_POST['confirm_account']);
    $ifsc_code = strtoupper(mysqli_real_escape_string($conn, $_POST['ifsc_code']));
    $branch = mysqli_real_escape_string($conn, $_POST['branch']);
    
    // Validate account number match
    if ($account_number != $confirm_account) {
        echo "<script>alert('Account numbers do not match!'); window.location.href = 'profile.php';</script>";
        exit();
    }
    
    // Validate account number (minimum 9 digits, maximum 18 digits)
    if (!preg_match('/^[0-9]{9,18}$/', $account_number)) {
        echo "<script>alert('Invalid account number! Must be 9-18 digits'); window.location.href = 'profile.php';</script>";
        exit();
    }
    
    // Validate IFSC code format (e.g., SBIN0123456)
    if (!preg_match('/^[A-Z]{4}0[A-Z0-9]{6}$/', $ifsc_code)) {
        echo "<script>alert('Invalid IFSC code! Format: SBIN0123456'); window.location.href = 'profile.php';</script>";
        exit();
    }
    
    // Check if bank_details table exists, if not create it
    $check_table = $conn->query("SHOW TABLES LIKE 'bank_details'");
    if ($check_table->num_rows == 0) {
        $create_table = "CREATE TABLE bank_details (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            bank_name VARCHAR(100) NOT NULL,
            account_holder VARCHAR(100) NOT NULL,
            account_number VARCHAR(20) NOT NULL,
            ifsc_code VARCHAR(20) NOT NULL,
            branch VARCHAR(100),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY unique_user (user_id)
        )";
        $conn->query($create_table);
    }
    
    // Check if record exists
    $check = $conn->query("SELECT * FROM bank_details WHERE user_id = $user_id");
    if ($check->num_rows > 0) {
        // Update existing
        $update_query = "UPDATE bank_details SET 
            bank_name = '$bank_name',
            account_holder = '$account_holder',
            account_number = '$account_number',
            ifsc_code = '$ifsc_code',
            branch = '$branch'
            WHERE user_id = $user_id";
    } else {
        // Insert new
        $update_query = "INSERT INTO bank_details 
            (user_id, bank_name, account_holder, account_number, ifsc_code, branch) 
            VALUES 
            ($user_id, '$bank_name', '$account_holder', '$account_number', '$ifsc_code', '$branch')";
    }
    
    if (mysqli_query($conn, $update_query)) {
        echo "<script>alert('Bank details updated successfully!'); window.location.href = 'profile.php';</script>";
    } else {
        echo "<script>alert('Error updating bank details: " . mysqli_error($conn) . "'); window.location.href = 'profile.php';</script>";
    }
}

// Handle password update
if (isset($_POST['profile_update_password'])) {
    $current_password = mysqli_real_escape_string($conn, $_POST['current_password']);
    $new_password = mysqli_real_escape_string($conn, $_POST['new_password']);
    $confirm_password = mysqli_real_escape_string($conn, $_POST['confirm_password']);
    
    // Verify current password
    if ($current_password != $details['password']) {
        echo "<script>alert('Current password is incorrect!'); window.location.href = 'profile.php';</script>";
        exit();
    }
    
    // Validate new password
    if (strlen($new_password) < 6) {
        echo "<script>alert('Password must be at least 6 characters'); window.location.href = 'profile.php';</script>";
        exit();
    }
    
    if ($new_password != $confirm_password) {
        echo "<script>alert('New password and confirm password do not match!'); window.location.href = 'profile.php';</script>";
        exit();
    }
    
    $update_query = "UPDATE users SET password = '$new_password' WHERE user_id = $user_id";
    
    if (mysqli_query($conn, $update_query)) {
        echo "<script>alert('Password updated successfully!'); window.location.href = 'profile.php';</script>";
    } else {
        echo "<script>alert('Error updating password: " . mysqli_error($conn) . "'); window.location.href = 'profile.php';</script>";
    }
}

// Fetch bank details if exists
$bank_details = null;
$bank_query = "SELECT * FROM bank_details WHERE user_id = $user_id";
$bank_result = $conn->query($bank_query);
if ($bank_result && $bank_result->num_rows > 0) {
    $bank_details = $bank_result->fetch_assoc();
}

// Get active tab from URL parameter
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'basic';
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title><?php echo htmlspecialchars($details['name']); ?> || Profile Settings</title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <!-- Favicons -->
  <link href="../img/logo/logo22222.png" rel="icon"> 

  <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
    
  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  
  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
  
  <style>
    :root {
      --primary-gradient: linear-gradient(135deg, #ad43cd 0%, #2d0759 100%);
      --primary-color: #ad43cd;
      --secondary-color: #2d0759;
    }

    body {
      background: #f4f7fc;
      font-family: 'Nunito', sans-serif;
    }

    .upload {
      width: 150px;
      position: relative;
      margin: 0 auto;
    }

    .upload img {
      border-radius: 50%;
      border: 4px solid var(--primary-color);
      width: 150px;
      height: 150px;
      object-fit: cover;
      transition: all 0.3s ease;
    }

    .upload img:hover {
      transform: scale(1.05);
      box-shadow: 0 10px 30px rgba(173, 67, 205, 0.3);
    }

    .upload .round {
      position: absolute;
      bottom: 5px;
      right: 5px;
      background: var(--primary-gradient);
      width: 40px;
      height: 40px;
      line-height: 42px;
      text-align: center;
      border-radius: 50%;
      overflow: hidden;
      cursor: pointer;
      box-shadow: 0 5px 15px rgba(173, 67, 205, 0.3);
      transition: all 0.3s ease;
    }

    .upload .round:hover {
      transform: scale(1.1);
      box-shadow: 0 8px 25px rgba(173, 67, 205, 0.5);
    }

    .upload .round i {
      color: white;
      font-size: 18px;
    }

    .upload .round input[type="file"] {
      position: absolute;
      transform: scale(2);
      opacity: 0;
      cursor: pointer;
    }

    .profile-card {
      background: white;
      border-radius: 20px;
      padding: 30px;
      box-shadow: 0 15px 35px rgba(0,0,0,0.1);
      transition: all 0.3s ease;
      margin-bottom: 25px;
    }

    .profile-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 25px 50px rgba(173, 67, 205, 0.15);
    }

    .info-card {
      background: #f8f9fa;
      border-radius: 15px;
      padding: 20px;
      margin-top: 20px;
    }

    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #e5e7eb;
    }

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

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

    .info-label i {
      color: var(--primary-color);
      width: 20px;
    }

    .info-value {
      color: #1f2937;
      font-weight: 500;
      background: white;
      padding: 5px 15px;
      border-radius: 30px;
      box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    }

    .tab-buttons {
      display: flex;
      gap: 10px;
      margin-bottom: 25px;
      flex-wrap: wrap;
    }

    .tab-btn {
      padding: 15px 30px;
      border: none;
      border-radius: 15px;
      font-weight: 600;
      font-size: 16px;
      cursor: pointer;
      transition: all 0.3s ease;
      background: white;
      color: #6b7280;
      box-shadow: 0 5px 15px rgba(0,0,0,0.05);
      display: flex;
      align-items: center;
      gap: 10px;
      flex: 1;
      min-width: 200px;
      justify-content: center;
    }

    .tab-btn i {
      font-size: 20px;
    }

    .tab-btn:hover {
      transform: translateY(-3px);
      box-shadow: 0 10px 25px rgba(173, 67, 205, 0.2);
    }

    .tab-btn.active {
      background: var(--primary-gradient);
      color: white;
      box-shadow: 0 10px 25px rgba(173, 67, 205, 0.4);
    }

    .settings-card {
      background: white;
      border-radius: 20px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.05);
      overflow: hidden;
      margin-bottom: 25px;
      animation: fadeIn 0.5s ease;
    }

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

    .settings-header {
      background: var(--primary-gradient);
      color: white;
      padding: 20px 25px;
      font-weight: 600;
      font-size: 18px;
    }

    .settings-body {
      padding: 30px;
    }

    .form-control-modern {
      width: 100%;
      padding: 12px 18px;
      border: 2px solid #e5e7eb;
      border-radius: 12px;
      font-size: 14px;
      transition: all 0.3s ease;
      background: white;
    }

    .form-control-modern:focus {
      border-color: var(--primary-color);
      box-shadow: 0 0 0 4px rgba(173, 67, 205, 0.1);
      outline: none;
    }

    .btn-modern {
      padding: 12px 30px;
      border: none;
      border-radius: 12px;
      font-weight: 600;
      font-size: 14px;
      transition: all 0.3s ease;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 8px;
    }

    .btn-primary-modern {
      background: var(--primary-gradient);
      color: white;
      box-shadow: 0 10px 20px rgba(173, 67, 205, 0.3);
    }

    .btn-primary-modern:hover {
      transform: translateY(-2px);
      box-shadow: 0 15px 30px rgba(173, 67, 205, 0.4);
    }

    .bank-status {
      display: inline-block;
      padding: 5px 12px;
      border-radius: 30px;
      font-size: 12px;
      font-weight: 600;
    }

    .bank-verified {
      background: #d1fae5;
      color: #065f46;
    }

    .bank-unverified {
      background: #fee2e2;
      color: #991b1b;
    }

    .tab-content {
      display: none;
    }

    .tab-content.active {
      display: block;
    }

    @media (max-width: 768px) {
      .profile-card {
        margin-bottom: 20px;
      }
      
      .info-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 5px;
      }
      
      .info-value {
        width: 100%;
        text-align: left;
      }

      .tab-btn {
        min-width: 100%;
      }
    }
  </style>
</head>

<body>

  <!-- ======= Header ======= -->
  <?php include 'element/header.php'; ?>
  
  <!-- ======= Sidebar ======= -->
  <?php include 'element/sidebar.php'; ?>

  <main id="main" class="main">
    <div class="pagetitle">
      <h1>Profile Settings</h1>
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="index.php">Home</a></li>
          <li class="breadcrumb-item active">Profile Settings</li>
        </ol>
      </nav>
    </div>

    <div class="row">
      <!-- Left Column - Profile Card -->
      <div class="col-xl-4 col-lg-4 col-md-5 col-sm-12 col-12">
        <div class="profile-card">
          <div class="upload">
            <form id="uploadForm" action="" enctype="multipart/form-data" method="post">
              <img src="profile-img/<?php echo htmlspecialchars($details['image']); ?>" alt="Profile Picture" id="profilePreview" onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($details['name']); ?>&background=ad43cd&color=fff&size=150'">
              <div class="round">
                <input type="file" name="image" id="image" accept=".jpg, .jpeg, .png">
                <i class="bi bi-camera"></i>
              </div>
            </form>
          </div>

          <div class="info-card">
            <div class="info-item">
              <span class="info-label"><i class="fas fa-user"></i> Name</span>
              <span class="info-value"><?php echo htmlspecialchars($details['name']); ?></span>
            </div>
            <div class="info-item">
              <span class="info-label"><i class="fas fa-id-card"></i> User ID</span>
              <span class="info-value"><?php echo $my_id; ?></span>
            </div>
            <div class="info-item">
              <span class="info-label"><i class="fas fa-phone"></i> Mobile</span>
              <span class="info-value"><?php echo $details['mobile'] ?: 'Not Set'; ?></span>
            </div>
            <div class="info-item">
              <span class="info-label"><i class="fas fa-map-marker-alt"></i> Address</span>
              <span class="info-value"><?php echo htmlspecialchars($details['address']) ?: 'Not Set'; ?></span>
            </div>
            <div class="info-item">
              <span class="info-label"><i class="fas fa-calendar"></i> Joined</span>
              <span class="info-value"><?php echo date('d M Y', strtotime($details['joining_date'])); ?></span>
            </div>
            <div class="info-item">
              <span class="info-label"><i class="fas fa-university"></i> Bank</span>
              <span class="info-value">
                <?php if ($bank_details): ?>
                  <span class="bank-status bank-verified"><i class="fas fa-check-circle me-1"></i> Added</span>
                <?php else: ?>
                  <span class="bank-status bank-unverified"><i class="fas fa-times-circle me-1"></i> Not Added</span>
                <?php endif; ?>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- Right Column - Settings with Tabs -->
      <div class="col-xl-8 col-lg-8 col-md-7 col-sm-12 col-12">
        <!-- Tab Buttons -->
        <div class="tab-buttons">
          <button class="tab-btn <?php echo $active_tab == 'basic' ? 'active' : ''; ?>" onclick="switchTab('basic')">
            <i class="fas fa-user-edit"></i> Basic Details
          </button>
          <button class="tab-btn <?php echo $active_tab == 'bank' ? 'active' : ''; ?>" onclick="switchTab('bank')">
            <i class="fas fa-university"></i> Bank Details
          </button>
          <button class="tab-btn <?php echo $active_tab == 'password' ? 'active' : ''; ?>" onclick="switchTab('password')">
            <i class="fas fa-lock"></i> Change Password
          </button>
        </div>

        <!-- Basic Details Tab -->
        <div id="basic-tab" class="tab-content <?php echo $active_tab == 'basic' ? 'active' : ''; ?>">
          <div class="settings-card">
            <div class="settings-header">
              <i class="fas fa-user-edit me-2"></i> Basic Details
            </div>
            <div class="settings-body">
              <form method="POST">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <label class="form-label">User ID</label>
                    <input type="text" class="form-control-modern" value="<?php echo $my_id ?>" readonly>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Sponsor ID</label>
                    <input type="text" class="form-control-modern" value="<?php echo $details['sponsor_id'] ?>" readonly>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Full Name</label>
                    <input type="text" class="form-control-modern" name="agent_name" value="<?php echo htmlspecialchars($details['name']) ?>" required>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Date of Birth</label>
                    <input type="date" class="form-control-modern" name="dob" value="<?php echo $details['dob'] ?>" required>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Gender</label>
                    <select class="form-control-modern" name="gender" required>
                      <option value="1" <?php echo ($details['gender']==1)?"selected":"" ?>>Male</option>
                      <option value="0" <?php echo ($details['gender']==0)?"selected":"" ?>>Female</option>
                    </select>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Mobile Number</label>
                    <input type="tel" class="form-control-modern" name="mob" value="<?php echo $details['mobile'] ?>" pattern="[0-9]{10}" placeholder="10 digit mobile number">
                  </div>
                  <div class="col-12 mb-3">
                    <label class="form-label">Address</label>
                    <textarea class="form-control-modern" name="address" rows="3"><?php echo htmlspecialchars($details['address']) ?></textarea>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">PAN Number</label>
                    <input type="text" class="form-control-modern" name="pan_no" value="<?php echo $details['panno'] ?>" 
                           oninput="this.value = this.value.toUpperCase()" 
                           placeholder="ABCDE1234F">
                    <small class="text-muted">Optional</small>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Aadhaar Number</label>
                    <input type="text" class="form-control-modern" name="aadhar_no" value="<?php echo $details['aadharno'] ?>" 
                           placeholder="123456789012" 
                           maxlength="12">
                    <small class="text-muted">Optional - 12 digits</small>
                  </div>
                </div>
                <div class="mt-4">
                  <button type="submit" name="profile_update_basic" class="btn-modern btn-primary-modern">
                    <i class="fas fa-save me-2"></i> Save Basic Details
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>

        <!-- Bank Details Tab -->
        <div id="bank-tab" class="tab-content <?php echo $active_tab == 'bank' ? 'active' : ''; ?>">
          <div class="settings-card">
            <div class="settings-header">
              <i class="fas fa-university me-2"></i> Bank Details
            </div>
            <div class="settings-body">
              <?php if ($bank_details): ?>
                <div class="alert alert-success mb-4">
                  <i class="fas fa-check-circle me-2"></i> Your bank details are saved.
                </div>
              <?php endif; ?>
              
              <form method="POST">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Bank Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control-modern" name="bank_name" 
                           value="<?php echo $bank_details ? htmlspecialchars($bank_details['bank_name']) : ''; ?>" 
                           placeholder="e.g., State Bank of India" required>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Account Holder Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control-modern" name="account_holder" 
                           value="<?php echo $bank_details ? htmlspecialchars($bank_details['account_holder']) : ''; ?>" 
                           placeholder="As per bank records" required>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Account Number <span class="text-danger">*</span></label>
                    <input type="text" class="form-control-modern" name="account_number" 
                           value="<?php echo $bank_details ? htmlspecialchars($bank_details['account_number']) : ''; ?>" 
                           placeholder="Enter account number" pattern="[0-9]{9,18}" maxlength="18" required>
                    <small class="text-muted">9-18 digits only</small>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Confirm Account Number <span class="text-danger">*</span></label>
                    <input type="text" class="form-control-modern" name="confirm_account" 
                           value="<?php echo $bank_details ? htmlspecialchars($bank_details['account_number']) : ''; ?>" 
                           placeholder="Re-enter account number" pattern="[0-9]{9,18}" maxlength="18" required>
                  </div>
                  <div class="col-md-4 mb-3">
                    <label class="form-label">IFSC Code <span class="text-danger">*</span></label>
                    <input type="text" class="form-control-modern" name="ifsc_code" 
                           value="<?php echo $bank_details ? htmlspecialchars($bank_details['ifsc_code']) : ''; ?>" 
                           oninput="this.value = this.value.toUpperCase()" 
                           placeholder="SBIN0123456" pattern="[A-Z]{4}0[A-Z0-9]{6}" maxlength="11" required>
                    <small class="text-muted">Format: SBIN0123456</small>
                  </div>
                  <div class="col-md-8 mb-3">
                    <label class="form-label">Branch</label>
                    <input type="text" class="form-control-modern" name="branch" 
                           value="<?php echo $bank_details ? htmlspecialchars($bank_details['branch']) : ''; ?>" 
                           placeholder="Branch name (optional)">
                  </div>
                </div>
                <div class="alert alert-info mt-3">
                  <i class="fas fa-info-circle me-2"></i>
                  Please ensure all bank details are correct. This information will be used for withdrawals.
                </div>
                <div class="mt-4">
                  <button type="submit" name="profile_update_bank" class="btn-modern btn-primary-modern">
                    <i class="fas fa-save me-2"></i> Save Bank Details
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>

        <!-- Password Change Tab -->
        <div id="password-tab" class="tab-content <?php echo $active_tab == 'password' ? 'active' : ''; ?>">
          <div class="settings-card">
            <div class="settings-header">
              <i class="fas fa-lock me-2"></i> Change Password
            </div>
            <div class="settings-body">
              <form method="POST">
                <div class="row">
                  <div class="col-md-4 mb-3">
                    <label class="form-label">Current Password <span class="text-danger">*</span></label>
                    <input type="password" class="form-control-modern" name="current_password" required>
                  </div>
                  <div class="col-md-4 mb-3">
                    <label class="form-label">New Password <span class="text-danger">*</span></label>
                    <input type="password" class="form-control-modern" name="new_password" required>
                  </div>
                  <div class="col-md-4 mb-3">
                    <label class="form-label">Confirm Password <span class="text-danger">*</span></label>
                    <input type="password" class="form-control-modern" name="confirm_password" required>
                  </div>
                </div>
                <div class="alert alert-info mt-3">
                  <i class="fas fa-info-circle me-2"></i>
                  Password must be at least 6 characters
                </div>
                <div class="mt-4">
                  <button type="submit" name="profile_update_password" class="btn-modern btn-primary-modern">
                    <i class="fas fa-key me-2"></i> Update Password
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>

  <!-- ======= Footer ======= -->
  <?php include('element/footer.php'); ?>

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center">
    <i class="bi bi-arrow-up-short"></i>
  </a>

  <!-- Vendor JS Files -->
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/jquery/jquery-3.6.0.min.js"></script>
  
  <!-- Template Main JS File -->
  <script src="assets/js/main.js"></script>

  <script>
    // Auto-submit form when image is selected
    document.getElementById("image").onchange = function() {
      if (this.files && this.files[0]) {
        // Show preview
        var reader = new FileReader();
        reader.onload = function(e) {
          document.getElementById('profilePreview').src = e.target.result;
        }
        reader.readAsDataURL(this.files[0]);
        
        // Submit form
        document.getElementById("uploadForm").submit();
      }
    };

    // Format PAN input
    document.querySelector('input[name="pan_no"]')?.addEventListener('input', function(e) {
      this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
    });

    // Format Aadhaar input (only numbers)
    document.querySelector('input[name="aadhar_no"]')?.addEventListener('input', function(e) {
      this.value = this.value.replace(/[^0-9]/g, '');
    });

    // Format mobile input (only numbers)
    document.querySelector('input[name="mob"]')?.addEventListener('input', function(e) {
      this.value = this.value.replace(/[^0-9]/g, '');
    });

    // Format account number (only numbers)
    document.querySelector('input[name="account_number"]')?.addEventListener('input', function(e) {
      this.value = this.value.replace(/[^0-9]/g, '');
    });

    document.querySelector('input[name="confirm_account"]')?.addEventListener('input', function(e) {
      this.value = this.value.replace(/[^0-9]/g, '');
    });

    // Format IFSC code
    document.querySelector('input[name="ifsc_code"]')?.addEventListener('input', function(e) {
      this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
    });

    // Switch tab function
    function switchTab(tabName) {
      // Update URL without page reload
      const url = new URL(window.location.href);
      url.searchParams.set('tab', tabName);
      window.history.pushState({}, '', url);
      
      // Hide all tabs
      document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
      });
      
      // Remove active class from all buttons
      document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
      });
      
      // Show selected tab
      document.getElementById(tabName + '-tab').classList.add('active');
      
      // Add active class to clicked button
      event.target.classList.add('active');
    }

    // Handle form submissions - keep the same tab after submission
    document.querySelectorAll('form').forEach(form => {
      form.addEventListener('submit', function() {
        const activeTab = document.querySelector('.tab-content.active').id.replace('-tab', '');
        const url = new URL(window.location.href);
        url.searchParams.set('tab', activeTab);
        window.location.href = url.toString();
      });
    });
  </script>

</body>
</html>