<?php require("header.php"); ?>
 
 <!--============START==PROFILE=====================================-->
 
 
 <?php

if (isset($_POST['profile'])) {
    try {
        // Sanitize input
        $password = htmlspecialchars($_POST['password']);
        $fullname = htmlspecialchars($_POST['fullname']);
        $username = htmlspecialchars($_POST['username']);
        $email = htmlspecialchars($_POST['email']);
        $phone = htmlspecialchars($_POST['phone']);
        $dob = htmlspecialchars($_POST['dob']);
        $sex = htmlspecialchars($_POST['sex']);
        $currency = htmlspecialchars($_POST['currency']);
        $cur_rate = htmlspecialchars($_POST['cur_rate']);
        $cur_symbol = htmlspecialchars($_POST['cur_symbol']);
        $country = htmlspecialchars($_POST['country']);
        $state = htmlspecialchars($_POST['state']);
        $city = htmlspecialchars($_POST['city']);
        $street1 = htmlspecialchars($_POST['street1']);
        $street2 = htmlspecialchars($_POST['street2']);
        $auto = htmlspecialchars($_POST['auto']);
        $id_no = htmlspecialchars($_POST['id_no']);
        $id_card = htmlspecialchars($_POST['id_card']);
        $exp_no = htmlspecialchars($_POST['exp_no']);

        // Ensure user is logged in before updating their profile
        if (!isset($_SESSION['SESS_USERID'])) {
            die("<div class='alert alert-danger'>User not authenticated.</div>");
        }
        $id = $_SESSION['SESS_USERID'];

        // Update user profile using PDO
        
        
        $stmt = $pdo->prepare("UPDATE logins SET 
            username = :username,
            fullname = :fullname,
            email = :email,
            phone = :phone,
            dob = :dob,
            sex = :sex,
            state = :state,
            city = :city,
            street1 = :street1,
            street2 = :street2
            WHERE id = :id");

       if ($stmt->execute([
            'username' => $username,
            'fullname' => $fullname,
            'email' => $email,
            'phone' => $phone,
            'dob' => $dob,
            'sex' => $sex,
            'state' => $state,
            'city' => $city,
            'street1' => $street1,
            'street2' => $street2,
            'id' => $id
        ]))

        // Success message
      
         {

       echo "<script>alert('Profile Successfully Updated!'); window.history.back();</script>";
        }

    } catch (PDOException $e) {
        echo "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
    }
}
?>



<!--=============END==PROFILE====================================-->
 
 
 
 
 
 
 
 
 
 <!--===================PHOTO==============================================-->
 
 
 
  <?php 

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES['imgPhoto'])) {
  // ==================IMAGE===========================          
              
             
 $maxsize = 104857600; // 100MB
//   if(isset($_FILES['imgPhoto']['name']) && $_FILES['imgPhoto']['name'] != ''){
    //   $name = $_FILES['imgPhoto']['name'];
      $target_dir = "accounts/upload/photo/";
      
      
      $target_file = $target_dir . basename($_FILES["imgPhoto"]["name"]);

      // Select imgPhoto type
      $extension = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

      // Valid imgPhoto extensions
      $extensions_arr = array( "jpg","png","jpeg", "gif", "jfif",);

      // Check extension
      if( in_array($extension,$extensions_arr) ){
 
          // Check imgPhoto size
          if(($_FILES['imgPhoto']['size'] >= $maxsize) || ($_FILES["imgPhoto"]["size"] == 0)) {
             $_SESSION['message'] = "File too large. File must be less than 100MB.";
          }
          
          else{
             
            	$sourcepath = $_FILES["imgPhoto"]["tmp_name"];
	$targetpath = "../accounts/upload/photo/" . $_FILES["imgPhoto"]["name"];
	move_uploaded_file($sourcepath,$targetpath);

	$P_location = "accounts/upload/photo/".$_FILES['imgPhoto']['name'];  
  
}
}                    

// Update database with the new file location
        $stmt = $pdo->prepare("UPDATE logins SET P_location = ? WHERE id = ?");
        if ($stmt->execute([$P_location, $id])) {
           
            // echo "<div class='alert alert-success'>Photo uploaded successfully!</div>";
            
            
             echo "<script>alert('Photo uploaded successfully!'); window.history.back();</script>";
             
            // echo "<meta http-equiv='refresh' content='2; url=index.php' />";
        } 
        
       
    }


?>


 
 
 
 <!--==================ENDS=======PHOTO=================================-->
 

<!--============Password=============================-->

<?php
if (isset($_POST['password_action'])) {
    $username = $_POST['username'];
    $password = $_POST['password']; // Current password entered by user
    $new_password = $_POST['cpassword']; // New password entered by user
    $id = $_SESSION['SESS_USERID']; // Fetching user ID from session

    // Fetch hashed password from DB
    $stmt = $pdo->prepare("SELECT password FROM logins WHERE id = :id AND username = :username");
    $stmt->execute(['id' => $id, 'username' => $username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['password'])) {
        // Hash new password
        $hashed_new_password = password_hash($new_password, PASSWORD_DEFAULT);

        // Update password and cpassword fields
        $updateStmt = $pdo->prepare("UPDATE logins SET password = :password, cpassword = :cpassword WHERE id = :id");
        $updateStmt->execute([
            'password' => $hashed_new_password,
            'cpassword' => $new_password, // store plain password if needed (not recommended)
            'id' => $id
        ]);

        echo "<script>
            alert('Password updated successfully!');
            window.location.href = 'index.php';
        </script>";
    } else {
        echo "<script>
            alert('Incorrect current password or username!');
            window.location.href = '';
        </script>";
    }
}
?>


<!--===========ends==password==================================-->








<main class="flex-1 px-2 py-4 md:p-6 bg-[#0B0A13] min-h-screen text-white">
    <div class="max-w-6xl mx-auto grid grid-cols-1 lg:grid-cols-3 gap-6">

        <!-- Avatar Card -->
        <div class="bg-[#141222] rounded-2xl p-6 text-center space-y-4">
            <img src="../<?= $P_location ?>" alt="Profile" class="w-24 h-24 mx-auto rounded-full object-cover border border-gray-700">
            <h2 class="text-xl font-semibold"><?= htmlspecialchars($user['fullname']) ?></h2>
            <p><i class="fa fa-wallet"></i> <?= $user['balance'] ?? 0 ?> <?= $user['cur_shot_name'] ?? '' ?></p>
            <form method="POST" enctype="multipart/form-data">
                <input type="file" name="imgPhoto" class="block w-full text-sm text-gray-400" accept="image/png,image/jpeg" required onchange="previewImage(event)">
                <div class="mt-3">
                    <img id="imagePreview" src="#" class="hidden mx-auto w-32 h-32 border border-gray-600 p-1 rounded">
                </div>
                <button type="submit" class="mt-3 w-full bg-[#2FE6DE] text-black py-2 rounded-xl">Update Avatar</button>
            </form>
        </div>

        <!-- Profile & Password Forms -->
        <div class="lg:col-span-2 space-y-6">

            <!-- Profile Form -->
            <div class="bg-[#141222] rounded-2xl p-6">
                <h2 class="text-xl font-semibold mb-4">Edit Profile</h2>
                <form method="POST" class="space-y-4">
                    <input type="hidden" name="profile" value="1">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <input type="text" name="fullname" value="<?= htmlspecialchars($user['fullname']) ?>" placeholder="Full Name" class="bg-[#1C1A2E] p-3 rounded-xl w-full">
                        <input type="text" name="username" value="<?= htmlspecialchars($user['username']) ?>" placeholder="Username" class="bg-[#1C1A2E] p-3 rounded-xl w-full">
                        <input type="email" name="email" value="<?= htmlspecialchars($user['email']) ?>" placeholder="Email" class="bg-[#1C1A2E] p-3 rounded-xl w-full">
                        <input type="tel" name="phone" value="<?= htmlspecialchars($user['phone']) ?>" placeholder="Phone" class="bg-[#1C1A2E] p-3 rounded-xl w-full">
                        <input type="date" name="dob" value="<?= htmlspecialchars($user['dob']) ?>" class="bg-[#1C1A2E] p-3 rounded-xl w-full">
                        <select name="sex" class="bg-[#1C1A2E] p-3 rounded-xl w-full">
                            <option value="1" <?= $user['sex']==1?'selected':'' ?>>Male</option>
                            <option value="2" <?= $user['sex']==2?'selected':'' ?>>Female</option>
                        </select>
                        <input type="text" name="state" value="<?= htmlspecialchars($user['state']) ?>" placeholder="State" class="bg-[#1C1A2E] p-3 rounded-xl w-full">
                        <input type="text" name="city" value="<?= htmlspecialchars($user['city']) ?>" placeholder="City" class="bg-[#1C1A2E] p-3 rounded-xl w-full">
                        <input type="text" name="street1" value="<?= htmlspecialchars($user['street1']) ?>" placeholder="Street 1" class="bg-[#1C1A2E] p-3 rounded-xl w-full">
                        <input type="text" name="street2" value="<?= htmlspecialchars($user['street2']) ?>" placeholder="Street 2" class="bg-[#1C1A2E] p-3 rounded-xl w-full">
                    </div>
                    <button type="submit" class="mt-4 w-full bg-[#2FE6DE] text-black py-2 rounded-xl">Update Profile</button>
                </form>
            </div>

            <!-- Password Change Form -->
            <div class="bg-[#141222] rounded-2xl p-6">
                <h2 class="text-xl font-semibold mb-4">Change Password</h2>
                <form method="POST" class="space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <input type="text" name="username" placeholder="Username" class="bg-[#1C1A2E] p-3 rounded-xl w-full" required>
                        <input type="password" name="password" placeholder="Current Password" class="bg-[#1C1A2E] p-3 rounded-xl w-full" required>
                        <input type="password" name="cpassword" placeholder="New Password" class="bg-[#1C1A2E] p-3 rounded-xl w-full" required>
                    </div>
                    <button type="submit" name="password_action" class="mt-4 w-full bg-[#F59E0B] py-2 rounded-xl font-semibold">Change Password</button>
                </form>
            </div>

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

<script>
function previewImage(event) {
    const reader = new FileReader();
    reader.onload = function(){
        const preview = document.getElementById('imagePreview');
        preview.src = reader.result;
        preview.classList.remove('hidden');
    }
    reader.readAsDataURL(event.target.files[0]);
}
</script>

<?php require("footer.php"); ?>
