<?php
include "header.php";
if (isset($_REQUEST['update'])) {
    
   

    // Assuming $mobile is already defined in header.php
    $sanitizedMobile =  $mobile;
    
    // Sanitize input using mysqli_real_escape_string
    $current_password =  $_REQUEST['current_password'];
    $new_password =  $_REQUEST['new_password'];
    $confirm_password =  $_REQUEST['confirm_password'];

    // Retrieve the hashed password from the database
    $query = "SELECT `password` FROM `users` WHERE `mobile` = '$sanitizedMobile'";
    $result = mysqli_query($conn, $query);
    
    if ($result) {
        $row = mysqli_fetch_assoc($result);
        $hashedPasswordFromDB = $row['password'];
        
        // Check if the current password matches the stored hashed password
        if (password_verify($current_password, $hashedPasswordFromDB)) {
            if ($new_password === $confirm_password) {
                // Hash the new password using bcrypt
                $newpass = password_hash($new_password, PASSWORD_DEFAULT);
                
                // Update the password in the database
                $passwor = "UPDATE `users` SET `password` = '$newpass' WHERE `mobile` = '$sanitizedMobile'";
                $up = mysqli_query($conn, $passwor);
                
                if ($up) {
                    // Password changed successfully
                    
                     echo '<script src="js/jquery-3.2.1.min.js"></script>';         echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';         echo '<script>         $("#loading_ajax").hide();
                        Swal.fire({
                            icon: "success",
                            title: "Password Changed Successfully",
                            text: "Your password has been updated.",
                            showConfirmButton: true,
                            confirmButtonText: "Ok",
                        }).then((result) => {
                            if (result.isConfirmed) {
                                window.location.href = "dashboard.php";
                            }
                        });
                    </script>';
                    exit;
                } else {
                    // Password update failed, handle the error
                    
                     echo '<script src="js/jquery-3.2.1.min.js"></script>';         echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';         echo '<script>         $("#loading_ajax").hide();
                        Swal.fire({
                            icon: "error",
                            title: "Password Update Failed",
                            text: "Please try again later.",
                            showConfirmButton: true,
                            confirmButtonText: "Try Again",
                        }).then((result) => {
                            if (result.isConfirmed) {
                                window.location.href = "changepassword.php";
                            }
                        });
                    </script>';
                    exit;
                }
            } else {
                // New Password and Confirm Password do not match
                
                 echo '<script src="js/jquery-3.2.1.min.js"></script>';         echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';         echo '<script>         $("#loading_ajax").hide();
                    Swal.fire({
                        icon: "error",
                        title: "New Password and Confirm Password Do Not Match",
                        showConfirmButton: true,
                        confirmButtonText: "Try Again",
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = "changepassword.php";
                        }
                    });
                </script>';
                exit;
            }
        } else {
            // Current Password does not match
            
             echo '<script src="js/jquery-3.2.1.min.js"></script>';         echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';         echo '<script>         $("#loading_ajax").hide();
                Swal.fire({
                    icon: "error",
                    title: "Current Password Does Not Match",
                    showConfirmButton: true,
                    confirmButtonText: "Try Again",
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = "changepassword.php";
                    }
                });
            </script>';
            exit;
        }
    } else {
        // Database query error
        
         echo '<script src="js/jquery-3.2.1.min.js"></script>';         echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';         echo '<script>         $("#loading_ajax").hide();
            Swal.fire({
                icon: "error",
                title: "Please try again later.",
                text: "Please try again later.",
                showConfirmButton: true,
                confirmButtonText: "Try Again",
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "changepassword.php";
                }
            });
        </script>';
        exit;
    }
}
?>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
        --success:#43e97b; --danger:#ff6584; --warning:#f5b93b;
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}

    .cpw-wrap{padding:20px;max-width:640px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .cpw-head{margin-bottom:22px}
    .cpw-head h1{font-size:1.5rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .cpw-head h1 .icn{
        width:38px;height:38px;border-radius:12px;background:var(--g);display:inline-flex;
        align-items:center;justify-content:center;font-size:16px;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .cpw-head p{font-size:.85rem;color:rgba(255,255,255,.45);margin:4px 0 0 48px}

    .glass-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;
    }
    .card-body{padding:26px}

    .form-group{margin-bottom:18px}
    .form-label{display:block;font-size:.78rem;font-weight:600;color:rgba(255,255,255,.5);margin-bottom:7px;text-transform:uppercase;letter-spacing:.3px}
    .pw-wrap{position:relative}
    .form-control{
        width:100%;background:rgba(255,255,255,.05);border:1.5px solid rgba(255,255,255,.1);border-radius:10px;
        padding:12px 44px 12px 14px;color:#fff;font-size:.9rem;outline:none;transition:.2s;font-family:'Inter',sans-serif;
    }
    .form-control:focus{border-color:var(--p);background:rgba(108,99,255,.08);box-shadow:0 0 0 3px rgba(108,99,255,.15)}
    .form-control::placeholder{color:rgba(255,255,255,.3)}
    .pw-toggle{
        position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;
        color:rgba(255,255,255,.35);cursor:pointer;font-size:.9rem;padding:4px;
    }
    .pw-toggle:hover{color:var(--p)}

    .match-hint{font-size:.76rem;margin-top:7px;display:flex;align-items:center;gap:6px;min-height:16px}
    .match-hint.ok{color:var(--success)}
    .match-hint.bad{color:var(--danger)}

    .strength-bar{height:4px;border-radius:3px;background:rgba(255,255,255,.08);margin-top:8px;overflow:hidden}
    .strength-fill{height:100%;width:0%;border-radius:3px;transition:.3s;background:var(--danger)}
    .strength-label{font-size:.72rem;color:rgba(255,255,255,.4);margin-top:5px}

    .btn-primary-cta{
        width:100%;background:var(--g);border:none;color:#fff;padding:13px;border-radius:10px;
        font-size:.9rem;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);margin-top:8px;
    }
    .btn-primary-cta:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45);color:#fff}

    .security-note{
        display:flex;gap:10px;background:rgba(108,99,255,.07);border:1px solid rgba(108,99,255,.2);
        border-radius:12px;padding:12px 14px;margin-top:20px;font-size:.78rem;color:rgba(255,255,255,.6);
    }
    .security-note i{color:var(--p);margin-top:2px;flex-shrink:0}
</style>

<div class="cpw-wrap">
    <div class="cpw-head">
        <h1><span class="icn"><i class="fas fa-lock"></i></span>Change Password</h1>
        <p>Keep your account secure with a strong password</p>
    </div>

    <div class="glass-card">
        <div class="card-body">
            <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" id="changePwForm">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

                <div class="form-group">
                    <label class="form-label">Current Password</label>
                    <div class="pw-wrap">
                        <input type="password" name="current_password" id="currentPw" placeholder="Current Password" class="form-control" required>
                        <button type="button" class="pw-toggle" onclick="togglePw('currentPw', this)"><i class="fas fa-eye"></i></button>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">New Password</label>
                    <div class="pw-wrap">
                        <input type="password" name="new_password" id="newPw" placeholder="New Password" class="form-control" required minlength="6">
                        <button type="button" class="pw-toggle" onclick="togglePw('newPw', this)"><i class="fas fa-eye"></i></button>
                    </div>
                    <div class="strength-bar"><div class="strength-fill" id="strengthFill"></div></div>
                    <div class="strength-label" id="strengthLabel">&nbsp;</div>
                </div>

                <div class="form-group">
                    <label class="form-label">Confirm Password</label>
                    <div class="pw-wrap">
                        <input type="password" name="confirm_password" id="confirmPw" placeholder="Confirm Password" class="form-control" required>
                        <button type="button" class="pw-toggle" onclick="togglePw('confirmPw', this)"><i class="fas fa-eye"></i></button>
                    </div>
                    <div class="match-hint" id="matchHint"></div>
                </div>

                <button type="submit" name="update" class="btn-primary-cta"><i class="fas fa-shield-halved"></i> Change Password</button>
            </form>

            <div class="security-note">
                <i class="fas fa-circle-info"></i>
                <span>Use at least 6 characters with a mix of letters, numbers, and symbols. Avoid reusing passwords from other accounts.</span>
            </div>
        </div>
    </div>
</div>

<script src="./assets/vendors/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="assets/js/app.min.js" type="text/javascript"></script>
<script src="./assets/js/scripts/dashboard_1_demo.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>
<script>
    function togglePw(id, btn) {
        var input = document.getElementById(id);
        var icon = btn.querySelector('i');
        if (input.type === 'password') {
            input.type = 'text';
            icon.className = 'fas fa-eye-slash';
        } else {
            input.type = 'password';
            icon.className = 'fas fa-eye';
        }
    }

    var newPw = document.getElementById('newPw');
    var confirmPw = document.getElementById('confirmPw');
    var strengthFill = document.getElementById('strengthFill');
    var strengthLabel = document.getElementById('strengthLabel');
    var matchHint = document.getElementById('matchHint');

    function scorePassword(pw) {
        var score = 0;
        if (pw.length >= 6) score++;
        if (pw.length >= 10) score++;
        if (/[A-Z]/.test(pw) && /[a-z]/.test(pw)) score++;
        if (/[0-9]/.test(pw)) score++;
        if (/[^A-Za-z0-9]/.test(pw)) score++;
        return score;
    }

    newPw.addEventListener('input', function() {
        var score = scorePassword(this.value);
        var pct = this.value.length === 0 ? 0 : Math.min(100, (score / 5) * 100);
        strengthFill.style.width = pct + '%';
        if (score <= 1) { strengthFill.style.background = '#ff6584'; strengthLabel.textContent = this.value ? 'Weak' : ''; }
        else if (score <= 3) { strengthFill.style.background = '#f5b93b'; strengthLabel.textContent = 'Medium'; }
        else { strengthFill.style.background = '#43e97b'; strengthLabel.textContent = 'Strong'; }
        checkMatch();
    });
    confirmPw.addEventListener('input', checkMatch);

    function checkMatch() {
        if (confirmPw.value === '') { matchHint.textContent = ''; matchHint.className = 'match-hint'; return; }
        if (newPw.value === confirmPw.value) {
            matchHint.innerHTML = '<i class="fas fa-check-circle"></i> Passwords match';
            matchHint.className = 'match-hint ok';
        } else {
            matchHint.innerHTML = '<i class="fas fa-circle-xmark"></i> Passwords do not match';
            matchHint.className = 'match-hint bad';
        }
    }
</script>
</body>
</html>
