<?php 
include("inc/header.php");

if($user_id == 0){
    echo "<script>window.location.href='login.php';</script>";
    exit;
}

/* ================= UPDATE PROFILE ================= */
if(isset($_POST['update_profile'])){

   $fullname = mysqli_real_escape_string($conn,$_POST['fullname']);
$email    = mysqli_real_escape_string($conn,$_POST['email']);
$phone    = mysqli_real_escape_string($conn,$_POST['phone']);
$password = mysqli_real_escape_string($conn,$_POST['password']);

    // OLD IMAGE
    $old_image = $_POST['old_image'];

    // DEFAULT
    $profile_image = $old_image;

    // IMAGE UPLOAD
    if(isset($_FILES['profile_image']) && $_FILES['profile_image']['name'] != ''){

        $img_name = time().'_'.$_FILES['profile_image']['name'];
        $tmp_name = $_FILES['profile_image']['tmp_name'];

        move_uploaded_file($tmp_name,"uploads/profile/".$img_name);

        $profile_image = $img_name;
    }

    // UPDATE WITH PASSWORD
    if(!empty($password)){

        $hashed_password = md5($password);

        mysqli_query($conn,"
            UPDATE tbl_register SET
name='$fullname',
email='$email',
phone='$phone',
password='$hashed_password',
profile_image='$profile_image'
WHERE id='$user_id'
        ");

    }else{

        // UPDATE WITHOUT PASSWORD
        mysqli_query($conn,"
           UPDATE tbl_register SET
name='$fullname',
email='$email',
phone='$phone',
profile_image='$profile_image'
WHERE id='$user_id'
        ");
    }

  $_SESSION['success'] = "Profile Updated Successfully";
echo "<script>window.location.href='';</script>";
exit;
}


/* ================= FETCH USER ================= */

$user_query = mysqli_query($conn,"SELECT * FROM tbl_register WHERE id='$user_id'");
$user = mysqli_fetch_assoc($user_query);

$username = $user['name'];
$email    = $user['email'];
$phone    = $user['phone'];
$created  = $user['created_date'];
$profile  = $user['profile_image'];
?>
<section class="inner-banner-row">
    <div class="container">
        <div class="inner-banner-sec"></div>
    </div>
</section>
<section class="sec5-row">
    <div class="container">
        <div class="row align-items-center">
            <!-- Sidebar -->
            <div class="col-lg-3 col-md-4">
                <div class="sidebar-box">
                    <ul class="sidebar-menu">
                        <li class="active" data-tab="dashboard">
                            <a href="javascript:void(0)">
                                <i class="fas fa-home"></i>
                                Dashboard
                            </a>
                        </li>
                        <li data-tab="orders">
                            <a href="javascript:void(0)">
                                <i class="fas fa-receipt"></i>
                                My Orders
                            </a>
                        </li>
                        <li data-tab="profile">
                            <a href="javascript:void(0)">
                                <i class="fas fa-user"></i>
                                Profile
                            </a>
                        </li>
                        <li>
                            <a href="logout.php">
                                <i class="fas fa-sign-out-alt"></i>
                                Logout
                            </a>
                        </li>
                    </ul>

                </div>
            </div>
            <!-- MAIN CONTENT -->
            <div class="col-lg-9 col-md-8">

                <div class="tab-content active-tab" id="dashboard">

                    <div class="welcome-card">

                        <div class="welcome-content">
                            <h2>Welcome back, <?php echo $username ?> 👋</h2>
                            <!-- <p>Your learning space, progress & updates — all in one place.</p> -->
                        </div>

                      <div class="welcome-user">

    <img id="welcomeProfileImg"
         src="<?php echo !empty($profile) ? 'uploads/profile/'.$profile : 'https://i.pravatar.cc/100'; ?>" 
         alt="">

</div>

                    </div>

                    <div class="row mt-4">

                        <div class="col-lg-4 mb-4">
                            <div class="stats-card">
                                <h5>Total Orders</h5>
                                <h2>3</h2>
                            </div>
                        </div>

                        <div class="col-lg-4 mb-4">
                            <div class="stats-card">
                                <h5>Pending Orders</h5>
                                <h2>0</h2>
                            </div>
                        </div>

                        <div class="col-lg-4 mb-4">
                            <div class="stats-card">
                                <h5>Completed Orders</h5>
                                <h2>0</h2>
                            </div>
                        </div>

                    </div>

                </div>
                <!-- Orders -->
                <div class="tab-content" id="orders">

                    <div class="content-box">
                        <div class="card mt-4">
                            <h4>My Orders</h4>
                            <div class="table-responsive mt-3">
                                <table class="table table-striped">

                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Order Id</th>
                                            <th>Product Name</th>
                                            <th>Product Desc</th>
                                            <th>Product Image</th>
                                            <th>Price</th>
                                            <th>Created At</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>1</td>
                                            <td>#123345</td>
                                            <td>1</td>
                                            <td>1</td>
                                            <td>0</td>
                                            <td>120</td>
                                            <td>12 Mar 2026, 13:25</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                </div>

                <!-- PROFILE -->
                <div class="tab-content" id="profile">

                    <div class="content-box">
                        <div class="profile-wrapper">
                            <!-- LEFT PROFILE CARD -->
<div class="profile-card">

    <div class="profile-img-wrap">

        <img id="profilePreview"
             class="profile-img" 
             src="<?php echo !empty($profile) ? 'uploads/profile/'.$profile : 'https://i.pravatar.cc/100'; ?>" 
             alt="">

        <label class="upload-btn">
            <i class="fa fa-camera"></i>

            <input type="file" 
                   name="profile_image"
                   form="profile-form"
                   id="profileUpload"
                   hidden>
        </label>

    </div>

    <h3><?php echo ucfirst($username) ?></h3>

</div>

                            <!-- RIGHT PROFILE FORM -->
                            <div class="profile-details card">
                                <h3 class="mb-4">Profile Information</h3>
                             <form method="POST" enctype="multipart/form-data" id="profile-form">

    <div class="row">

        <div class="col-md-6 mb-3">
            <label>Full Name</label>
            <input type="text" 
                   name="fullname" 
                   class="form-control"
                   value="<?php echo $username; ?>">
                   <input type="hidden" name="old_image" value="<?php echo $profile; ?>">
        </div>

        <div class="col-md-6 mb-3">
            <label>Email</label>
            <input type="email" 
                   name="email"
                   class="form-control"
                   value="<?php echo $email; ?>">
        </div>

        <!-- CHANGE PASSWORD BUTTON -->
        <div class="col-md-12 mb-3">
            <span id="showPasswordBox"
                  style="cursor:pointer;color:#eb192e;font-weight:600;text-decoration: underline;">
                Change Password
            </span>
        </div>

        <!-- PASSWORD FIELD HIDDEN -->
        <div class="col-md-12 mb-3" id="passwordBox" style="display:none;">
            <label>New Password</label>
            <input type="password" 
                   name="password"
                   class="form-control"
                   placeholder="Enter new password">
        </div>

       <div class="col-md-6 mb-3">
    <label>Phone Number</label>

    <input type="text" 
           name="phone"
           id="phone"
           class="form-control"
           value="<?php echo $phone; ?>"
           placeholder="+0000-000-000"
           maxlength="13">
</div>


        <div class="col-md-6 mb-3">
            <label>Member Since</label>
            <input type="text"
       id="memberSince"
       class="form-control"
       value="<?php echo date('d M Y h:i A', strtotime($created)); ?>" readonly>
        </div>

        <div class="col-md-12 mt-3">
            <button type="submit" 
                    name="update_profile"
                    class="btn btn-dark px-4 updatebtn">
                Update Profile
            </button>
        </div>

    </div>

</form>
                            </div>

                        </div>
                    </div>

                </div>


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


<?php include("inc/footer.php"); ?>
<?php if(isset($_SESSION['success'])){ ?>

<script>
toastr.success('<?php echo $_SESSION['success']; ?>','Success');
</script>

<?php unset($_SESSION['success']); } ?>
<script>
document.getElementById('profileUpload').addEventListener('change', function(e){

    const file = e.target.files[0];

    if(file){

        const reader = new FileReader();

        reader.onload = function(event){

            // PROFILE CARD IMAGE
            document.getElementById('profilePreview').src = event.target.result;

            // WELCOME TOP IMAGE
            document.getElementById('welcomeProfileImg').src = event.target.result;
        }

        reader.readAsDataURL(file);
    }

});


document.getElementById('showPasswordBox').addEventListener('click', function(){

    let box = document.getElementById('passwordBox');

    if(box.style.display == 'none'){
        box.style.display = 'block';
    }else{
        box.style.display = 'none';
    }

});

document.getElementById('phone').addEventListener('input', function(e){

    // REMOVE NON NUMBERS
    let numbers = e.target.value.replace(/\D/g,'');

    // LIMIT 10 DIGITS
    numbers = numbers.substring(0,10);

    let formatted = '';

    // +0000
    if(numbers.length > 0){
        formatted = '+' + numbers.substring(0,4);
    }

    // -000
    if(numbers.length >= 5){
        formatted += '-' + numbers.substring(4,7);
    }

    // -000
    if(numbers.length >= 8){
        formatted += '-' + numbers.substring(7,10);
    }

    e.target.value = formatted;

});

// DISABLE MEMBER SINCE FIELD
document.getElementById('memberSince').addEventListener('keydown', function(e){
    e.preventDefault();
});

document.getElementById('memberSince').addEventListener('paste', function(e){
    e.preventDefault();
});

document.getElementById('memberSince').addEventListener('focus', function(){
    this.blur();
});
</script>