<?php
include 'header.php'; 

// Alert functions
function show_error($message) {
    return "<script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: '".addslashes($message)."'
            });
        });
    </script>";
}

function show_success($message) {
    return "<script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: '".addslashes($message)."'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'account_edit.php';
                }
            });
        });
    </script>";
}


$alert = '';
// Handle account information update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['savechages'])) {
    $phone_no = $_POST['phone_no'];
    $street_address = $_POST['street_address'];
    $state = $_POST['state'];
    $country = $_POST['country'];
    $btcadd = $_POST['btc_add'];
    $ethadd = $_POST['eth_add'];
    
    // Initialize variables
    $profile_picture = $user_data['profile_picture'] ?? '';
    $update_profile_pic = false;
    
    // Handle file upload only if a file was actually selected and valid
    if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['profile_picture'];
        $upload_dir = '../uploads/profile_pictures/';
        
        // Create directory if it doesn't exist
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        $file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $new_filename = 'profile_' . $user_id . '_' . time() . '.' . $file_ext;
        $upload_path = $upload_dir . $new_filename;
        
        if (move_uploaded_file($file['tmp_name'], $upload_path)) {
            // Delete old profile picture if exists
            if (!empty($user_data['profile_picture']) && file_exists($user_data['profile_picture'])) {
                unlink($user_data['profile_picture']);
            }
            $profile_picture = $upload_path;
            $update_profile_pic = true;
        }
    }
    
    // Update database - only include profile_picture in the query if it was updated
    if ($update_profile_pic) {
        $sql = "UPDATE users SET 
                phone_no = ?, 
                street_address = ?, 
                state = ?, 
                country = ?, 
                btc_add = ?, 
                eth_add = ?, 
                profile_picture = ? 
                WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssssi", $phone_no, $street_address, $state, $country, $btcadd, $ethadd, $profile_picture, $user_id);
    } else {
        $sql = "UPDATE users SET 
                phone_no = ?, 
                street_address = ?, 
                state = ?, 
                country = ?, 
                btc_add = ?, 
                eth_add = ? 
                WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssssi", $phone_no, $street_address, $state, $country, $btcadd, $ethadd, $user_id);
    }
    
    if ($stmt->execute()) {
        $alert = show_success("Account information updated successfully!");
        // Refresh user data
        $sql = "SELECT * FROM users WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $user_data = $result->fetch_assoc();
    } else {
        $alert = show_error("Error updating account information: " . $conn->error);
    }
    $stmt->close();
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['old_password'])) {
    $old_password = $_POST['old_password'];
    $new_password = $_POST['password'];
    $confirm_password = $_POST['password_confirmation'];
    
    // Verify old password
    $sql = "SELECT password FROM users WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $db_password = $result->fetch_assoc()['password'];
    $stmt->close();
    
    if (password_verify($old_password, $db_password)) {
        if ($new_password === $confirm_password) {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $sql = "UPDATE users SET password = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("si", $hashed_password, $user_id);
            
            if ($stmt->execute()) {
                $alert = show_success("Password changed successfully!");
            } else {
                $alert = show_error("Error changing password: " . $conn->error);
            }
            $stmt->close();
        } else {
            $alert = show_error("New password and confirmation don't match!");
        }
    } else {
        $alert = show_error("Old password is incorrect!");
    }
}

$conn->close();
?>


    

    
    <div class="pt-28 md:pt-0 mt-0 md:mt-36 w-full md:w-4/5" id="general-content">
        <div class="w-full md:w-10/12 md:ml-64 2xl:ml-1/5" id="general-content-section">

            
            <div class="w-full py-5">
    <div class="w-full flex justify-center">
        <div class="w-11/12 rounded-md bg-[#0e1726] p-2 md:p-4">
            <div class="flex justify-between items-center">
                <div>
                    
                    <h2 class="bg-transparent text-[#ebedf2] font-medium capitalize">
                        Edit Profile
                    </h2>
                </div>

                <div>
                    <a href="javascript:history.back()" class="flex justify-start items-center text-xs text-gray-400 hover:text-white">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M11 17l-5-5m0 0l5-5m-5 5h12" />
                        </svg>
                        <span>back</span>
                    </a>

                </div>
            </div>
        </div>
    </div>
</div>
            

            
            <div id="preloader" class="action-preloader">
    <div id="loading-bar-spinner" class="spinner">
        <div class="spinner-icon"></div>
    </div>
</div>

            
            
            
                        

            
                        

         <div class="w-full py-5">
    <div class="w-full flex justify-center">
        <div class="w-11/12 rounded-md bg-[#0e1726] p-2 md:p-4">
            <div class="w-full flex justify-start items-baseline space-x-2">
                <h6 class="bg-transparent text-center text-[#ebedf2] text-xs md:text-sm capitalize">
                    Account Information
                </h6>
            </div>

            <hr class="w-full border-b border-dotted border-gray-600 border">

         

            <form class="w-full mt-2 p-2 md:p-4 space-y-4" action="" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                
                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-28 overflow-hidden" for="first_name">First Name:</label>
                        <input class="flex-grow px-2 md:px-4 pt-2 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" type="text" value="<?php echo htmlspecialchars($first_name); ?>" disabled>
                    </div>
                </div>

                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-28 overflow-hidden" for="last_name">Last Name:</label>
                        <input class="flex-grow px-2 md:px-4 pt-4 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" type="text" value="<?php echo htmlspecialchars($last_name); ?>" disabled>
                    </div>
                </div>

                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-28 overflow-hidden" for="dob">Date Of Birth:</label>
                        <input class="flex-grow px-2 md:px-4 pt-4 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" type="date" disabled value="<?php echo htmlspecialchars($dob); ?>">
                    </div>
                </div>
                
                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-28 overflow-hidden" for="phone_no">Phone No:</label>
                        <input class="flex-grow px-2 md:px-4 pt-4 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" type="tel" name="phone_no" id="phone_no" value="<?php echo htmlspecialchars($phone_no); ?>">
                    </div>
                    <span class="p-1 text-red-600"></span>
                </div>

                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-28 overflow-hidden" for="street_address">Address:</label>
                        <textarea class="flex-grow px-2 md:px-4 pt-2 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" name="street_address" id="street_address"><?php echo htmlspecialchars($street_address); ?></textarea>
                    </div>
                    <span class="p-1 text-red-600"></span>
                </div>

                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-28 overflow-hidden" for="phone_no">State</label>
                        <input class="flex-grow px-2 md:px-4 pt-2 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" type="text" name="state" id="state" value="<?php echo htmlspecialchars($state); ?>">
                    </div>
                    <span class="p-1 text-red-600"></span>
                </div>

                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-28 overflow-hidden" for="country">Country:</label>
                        <select class="flex-grow px-2 md:px-4 pt-2 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" name="country">
                            <?php
                            $countries = [
                                "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", 
                                "Antigua & Deps", "Argentina", "Armenia", "Australia", "Austria",
                                "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados",
                                "Belarus", "Belgium", "Belize", "Benin", "Bhutan",
                                "Bolivia", "Bosnia Herzegovina", "Botswana", "Brazil", "Brunei",
                                "Bulgaria", "Burkina", "Burundi", "Cambodia", "Cameroon",
                                "Canada", "Cape Verde", "Central African Rep", "Chad", "Chile",
                                "China", "Colombia", "Comoros", "Congo", "Congo {Democratic Rep}",
                                "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
                                "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor",
                                "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
                                "Estonia", "Ethiopia", "Fiji", "Finland", "France",
                                "Gabon", "Gambia", "Georgia", "Germany", "Ghana",
                                "Greece", "Grenada", "Guatemala", "Guinea", "Guinea-Bissau",
                                "Guyana", "Haiti", "Honduras", "Hungary", "Iceland",
                                "India", "Indonesia", "Iran", "Iraq", "Ireland {Republic}",
                                "Israel", "Italy", "Ivory Coast", "Jamaica", "Japan",
                                "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea North",
                                "Korea South", "Kosovo", "Kuwait", "Kyrgyzstan", "Laos",
                                "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya",
                                "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Madagascar",
                                "Malawi", "Malaysia", "Maldives", "Mali", "Malta",
                                "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia",
                                "Moldova", "Monaco", "Mongolia", "Montenegro", "Morocco",
                                "Mozambique", "Myanmar, {Burma}", "Namibia", "Nauru", "Nepal",
                                "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria",
                                "Norway", "Oman", "Pakistan", "Palau", "Panama",
                                "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland",
                                "Portugal", "Qatar", "Romania", "Russian Federation", "Rwanda",
                                "St Kitts & Nevis", "St Lucia", "Saint Vincent & the Grenadines", "Samoa", "San Marino",
                                "Sao Tome & Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles",
                                "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
                                "Somalia", "South Africa", "South Sudan", "Spain", "Sri Lanka",
                                "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland",
                                "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand",
                                "Togo", "Tonga", "Trinidad & Tobago", "Tunisia", "Turkey",
                                "Turkmenistan", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates",
                                "United Kingdom", "United States", "Uruguay", "Uzbekistan", "Vanuatu",
                                "Vatican City", "Venezuela", "Vietnam", "Yemen", "Zambia",
                                "Zimbabwe"
                            ];
                            
                            foreach ($countries as $country_option) {
                                $selected = ($country_option == $country) ? 'selected' : '';
                                echo "<option value=\"" . htmlspecialchars($country_option) . "\" $selected>" . htmlspecialchars($country_option) . "</option>";
                            }
                            ?>
                        </select>
                    </div>
                    <span class="p-1 text-red-600"></span>
                </div>
                
                
                
                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-28 overflow-hidden" for="btc_add">BTC Address</label>
                        <input class="flex-grow px-2 md:px-4 pt-2 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" type="text" name="btc_add" id="btc_add" value="<?php echo htmlspecialchars($btc_add); ?>">
                    </div>
                    <span class="p-1 text-red-600"></span>
                </div>
                
                        
                
                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-28 overflow-hidden" for="eth_add">ETH Address</label>
                        <input class="flex-grow px-2 md:px-4 pt-2 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" type="text" name="eth_add" id="eth_add" value="<?php echo htmlspecialchars($eth_add); ?>">
                    </div>
                    <span class="p-1 text-red-600"></span>
                </div>
                
                        
                
     


                <div class="text-[#bfc9d4] text-xs md:text-sm mt-2">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-28 overflow-hidden" for="profile_picture">Profile Picture:</label>
                        <label class="font-medium py-1 flex flex-grow justify-center items-center space-x-2 border rounded-sm border-slate-800 hover:border-slate-600 cursor-pointer" for="profile_picture">
                            <h5>select image</h5>
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
                                <path stroke-linecap="round" stroke-linejoin="round" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
                            </svg>
                        </label>
                        <input class="hidden" type="file" name="profile_picture" id="profile_picture">
                    </div>
                    <?php if (!empty($user_data['profile_picture'])): ?>
                        <div class="mt-2">
                            <img src="<?php echo htmlspecialchars($user_data['profile_picture']); ?>" alt="Profile Picture" class="h-20 w-20 rounded-full object-cover">
                        </div>
                    <?php endif; ?>
                    <span class="p-1 text-red-600"></span>
                </div>

                <div class="w-full my-5 px-5">
                    <button type="submit" name='savechages' class="w-full text-xs md:text-sm text-[#d1d5db] text-center px-5 py-3 my-5 bg-[#1b2e4b] hover:bg-gray-700 rounded-md">
                        Save changes
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="w-full py-5">
    <div class="w-full flex justify-center">
        <div class="w-11/12 rounded-md bg-[#0e1726] p-2 md:p-4">
            <div class="w-full flex justify-start items-baseline space-x-2">
                <h6 class="bg-transparent text-center text-[#ebedf2] text-xs md:text-sm capitalize">
                    Change Password
                </h6>
            </div>

            <hr class="w-full border-b border-dotted border-gray-600 border">

            <?php if (isset($password_success)): ?>
                <div class="text-green-500 text-sm mb-4"><?php echo $password_success; ?></div>
            <?php endif; ?>
            <?php if (isset($password_error)): ?>
                <div class="text-red-500 text-sm mb-4"><?php echo $password_error; ?></div>
            <?php endif; ?>

            <form class="w-full mt-2 p-2 md:p-4 space-y-4" action="" method="POST">
                <input type="hidden" name="_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                <div class="text-[#bfc9d4] text-xs md:text-sm mb-1">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-32 overflow-hidden" for="old_password">Old Password:</label>
                        <input class="flex-grow px-2 md:px-4 pt-2 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" type="password" name="old_password" id="old_password" required>
                    </div>
                    <span class="p-1 text-red-600"></span>
                </div>

                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-32 overflow-hidden" for="password">New Password:</label>
                        <input class="flex-grow px-2 md:px-4 pt-4 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" type="password" name="password" id="password" required>
                    </div>
                    <span class="p-1 text-red-600"></span>
                </div>

                <div class="text-[#bfc9d4] text-xs md:text-sm">
                    <div class="w-full flex items-baseline space-x-1">
                        <label class="font-medium w-32 overflow-hidden" for="password_confirmation">Confirm Password:</label>
                        <input class="flex-grow px-2 md:px-4 pt-4 bg-[#0e1726] transition-colors duration-200 transform focus:outline-none border-b-2 border-slate-800 focus:border-b-slate-500" type="password" name="password_confirmation" id="password_confirmation" required>
                    </div>
                    <span class="p-1 text-red-600"></span>
                </div>

                <div class="w-full my-5 px-5">
                    <button type="submit" class="w-full text-xs md:text-sm text-[#d1d5db] text-center px-5 py-3 my-5 bg-[#1b2e4b] hover:bg-gray-700 rounded-md">
                        Change password
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>


        </div>
    </div>
    
</div>


<?php echo $alert; ?>
<?php
    include 'footer.php';
?>