<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

//include("../config/theconfig.php");
include("header.php");

// Redirect if not logged in
if (!isset($_SESSION['customerid'])) {
    header('Location: login.php?error=nologin');
    exit();
}

// Assume your existing mysqli connection is available here as $con

// Handle form submission
$message = '';
$alertType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['button'])) {
    // Sanitize and validate input
    $oldPass = mysqli_real_escape_string($con, trim($_POST['oldpass'] ?? ''));
    $newPass = mysqli_real_escape_string($con, trim($_POST['newpass'] ?? ''));
    $confPass = mysqli_real_escape_string($con, trim($_POST['confpass'] ?? ''));
    $customerId = $_SESSION['customerid'];

    if (empty($oldPass) || empty($newPass) || empty($confPass)) {
        $message = 'All fields are required.';
        $alertType = 'error';
    } elseif ($newPass !== $confPass) {
        $message = 'The new password and confirm password fields do not match.';
        $alertType = 'error';
    } elseif (strlen($newPass) < 8) {
        $message = 'New password must be at least 8 characters long.';
        $alertType = 'error';
    } else {
        // Fetch the current plain text password from the database
        $sql = "SELECT accpassword FROM customers WHERE customerid = '$customerId'";
        $result = mysqli_query($con, $sql);
        $user = mysqli_fetch_assoc($result);

        // Compare the submitted plain text password with the stored plain text password
        if ($user && ($oldPass === $user['accpassword'])) {
            // Passwords match, now update the new plain text password
            $updateSql = "UPDATE customers SET accpassword = '$newPass' WHERE customerid = '$customerId'";

            if (mysqli_query($con, $updateSql)) {
                $message = 'Your new password has been updated successfully!';
                $alertType = 'success';
            } else {
                $message = 'Password update was not successful. Please try again.';
                $alertType = 'error';
            }
        } else {
            $message = 'Incorrect current password.';
            $alertType = 'error';
        }
    }
}
?>

<html lang="en">
   <head>
      <meta charset="utf-8" />
      <title>Update Password | <?php echo htmlspecialchars($sbank); ?></title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta content="<?php echo htmlspecialchars($sbank); ?>" name="description" />
      <meta content="<?php echo htmlspecialchars($sbank); ?>" name="author" />
      
      <?php if (!empty($favicon)): ?>
      <link rel="icon" href="../<?= htmlspecialchars($favicon); ?>" type="image/<?= pathinfo($favicon, PATHINFO_EXTENSION); ?>">
      <?php endif; ?>
      
      <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
      <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
      <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
      
      <link rel="preconnect" href="https://fonts.googleapis.com">
      <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
      <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
      
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.1.9/dist/sweetalert2.min.css">
      
    <style>
    /* --- PREMIUM BLUE THEME --- */
    :root {
        --primary-purple: #003399; /* Primary Blue */
        --dark-purple: #005D9D;    /* Secondary Blue */
        --soft-purple-bg: #e6efff; /* Light Blue background for icons/focus */
        --bg-body: #f8fafc;
        --text-main: #0f172a;
        --text-secondary: #64748b;
    }

    body {
        font-family: 'Plus Jakarta Sans', sans-serif;
        background-color: var(--bg-body);
        color: var(--text-main);
    }

    .page-content { padding-top: 80px; }
    .swal-text { font-size: 13px; }

    .card {
        border: none;
        border-radius: 24px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
        background: #fff;
        overflow: hidden;
    }

    .card-body { padding: 40px; }

    .pass-header {
        text-align: center;
        margin-bottom: 30px;
    }
    
    .pass-icon-bg {
        width: 80px;
        height: 80px;
        background: var(--soft-purple-bg);
        color: var(--primary-purple);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 36px;
        margin: 0 auto 20px;
    }

    /* Password strength UI styles */
    .password-meter {
      height: 5px;
      background: #e2e8f0;
      border-radius: 5px;
      margin-top: 10px;
      overflow: hidden;
    }
    .password-meter-fill {
      height: 100%;
      border-radius: 5px;
      transition: width 0.3s ease-in-out, background-color 0.3s ease-in-out;
    }
    
    .password-rules {
      list-style: none;
      padding: 0;
      margin-top: 15px;
      font-size: 12px;
      color: var(--text-secondary);
    }
    
    .form-control {
      border-radius: 12px !important;
      padding: 12px 16px;
      border: 1px solid #e2e8f0;
      height: 50px;
    }
    
    .form-control:focus {
      border-color: var(--primary-purple) !important;
      box-shadow: 0 0 0 4px var(--soft-purple-bg) !important;
    }
    
    .password-container {
        position: relative;
        width: 100%;
    }
    
    .password-container .toggle-icon:hover { color: var(--primary-purple); }

    .btn-primary {
        background-color: var(--primary-purple);
        border: none;
        border-radius: 12px;
        padding: 14px;
        font-weight: 700;
        width: 100%;
        transition: all 0.3s ease;
        font-size: 1rem;
        /* Updated Shadow to Blue */
        box-shadow: 0 4px 12px rgba(0, 51, 153, 0.3);
    }

    .btn-primary:hover {
        background-color: var(--dark-purple);
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(0, 51, 153, 0.4);
    }

    /* Breadcrumb color override */
    .text-purple { color: var(--primary-purple) !important; }
</style>
   </head>

   <body data-sidebar="colored">
      <div id="preloader"> <div id="status"> <div class="spinner-chase"> <div class="chase-dot"></div> <div class="chase-dot"></div> <div class="chase-dot"></div> <div class="chase-dot"></div> <div class="chase-dot"></div> <div class="chase-dot"></div> </div> </div> </div>
      
      <div id="layout-wrapper">
         <div class="main-content">
            <div class="page-content">
               <div class="container-fluid">
                  
                  <div class="row mb-4">
                      <div class="col-12">
                          <div class="d-flex align-items-center justify-content-between">
                              <div>
                                  <h4 class="mb-1 fw-bold text-dark">Security Settings</h4>
                                  <p class="text-secondary mb-0">Secure Your Account Password.</p>
                              </div>
                              <div class="d-none d-md-block">
                                  <nav aria-label="breadcrumb">
                                      <ol class="breadcrumb m-0">
                                          <li class="breadcrumb-item"><a href="dashboard.php" class="text-decoration-none text-muted">Dashboard</a></li>
                                          <li class="breadcrumb-item active text-purple fw-bold">Password</li>
                                      </ol>
                                  </nav>
                              </div>
                          </div>
                      </div>
                  </div>

                  <div class="row justify-content-center">
                     <div class="col-xl-6 col-lg-8">
                        <div class="card">
                           <div class="card-body">
                              
                              <div class="pass-header">
                                  <div class="pass-icon-bg">
                                      <i class="mdi mdi-lock-outline"></i>
                                  </div>
                                  <h4 class="fw-bold mb-1 text-dark">Change Login Password</h4>
                                  <p class="text-muted small">Update your password to keep your account safe.</p>
                              </div>

                              <form id="passwordForm" method="post" action="">
                                 
                                 <div class="mb-4">
                                    <label for="oldpass" class="form-label fw-bold text-secondary small text-uppercase">Current Password</label>
                                    <div class="password-container">
                                       <input type="password" name="oldpass" size="35" class="form-control" id="oldpass" placeholder="Enter Current Password">
                                       <i class="mdi mdi-eye-outline toggle-icon"></i>
                                    </div>
                                 </div>

                                 <div class="mb-4">
                                    <label for="newpass" class="form-label fw-bold text-secondary small text-uppercase">New Password</label>
                                    <div class="password-container">
                                       <input required name="newpass" type="password" id="newpass" class="form-control" placeholder="New Password">
                                       <i class="mdi mdi-eye-outline toggle-icon"></i>
                                    </div>
                                    
                                    <div class="password-meter">
                                       <div id="strength-bar" class="strength-bar"></div>
                                    </div>
                                    
                                    <ul class="password-rules" id="password-rules">
                                       <li id="rule-length" class="invalid">At least 8 characters</li>
                                       <li id="rule-uppercase" class="invalid">An uppercase letter</li>
                                       <li id="rule-number" class="invalid">A number</li>
                                       <li id="rule-special" class="invalid">A special character</li>
                                    </ul>
                                 </div>

                                 <div class="mb-4">
                                    <label for="confpass" class="form-label fw-bold text-secondary small text-uppercase">Confirm New Password</label>
                                    <div class="password-container">
                                       <input class="form-control" required name="confpass" type="password" id="confpass" placeholder="Confirm New Password">
                                       <i class="mdi mdi-eye-outline toggle-icon"></i>
                                    </div>
                                 </div>
                                 
                                 <div class="mt-5">
                                    <button type="submit" name="button" id="button" class="btn btn-primary">
                                        Update Password <i class="mdi mdi-check-circle-outline ms-1"></i>
                                    </button>
                                 </div>
                              </form>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
            <?php include 'footer.php' ?>
         </div>
      </div>
      
      <script src="assets/libs/jquery/jquery.min.js"></script>
      <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
      <script src="assets/libs/simplebar/simplebar.min.js"></script>
      <script src="assets/libs/node-waves/waves.min.js"></script>
      <script src="assets/js/app.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.1.9/dist/sweetalert2.all.min.js"></script>
      
      <script>
         document.addEventListener('DOMContentLoaded', function() {
             const passwordForm = document.getElementById('passwordForm');
             const newPassInput = document.getElementById('newpass');
             const confPassInput = document.getElementById('confpass');
             const strengthBar = document.getElementById('strength-bar');
             
             // Rules Elements
             const rules = {
                 length: document.getElementById('rule-length'),
                 uppercase: document.getElementById('rule-uppercase'),
                 number: document.getElementById('rule-number'),
                 special: document.getElementById('rule-special')
             };
             const specialCharacters = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;

             function checkPasswordStrength(password) {
                 let score = 0;

                 const isLengthValid = password.length >= 8;
                 const hasUppercase = /[A-Z]/.test(password);
                 const hasNumber = /[0-9]/.test(password);
                 const hasSpecial = specialCharacters.test(password);

                 // Update Rules UI
                 if (rules.length) rules.length.className = isLengthValid ? 'valid' : 'invalid';
                 if (rules.uppercase) rules.uppercase.className = hasUppercase ? 'valid' : 'invalid';
                 if (rules.number) rules.number.className = hasNumber ? 'valid' : 'invalid';
                 if (rules.special) rules.special.className = hasSpecial ? 'valid' : 'invalid';

                 if (isLengthValid) score++;
                 if (hasUppercase) score++;
                 if (hasNumber) score++;
                 if (hasSpecial) score++;

                 const strengthColors = ['#dc3545', '#ffc107', '#28a745', '#198754'];
                 const barWidths = ['25%', '50%', '75%', '100%'];

                 let level = Math.max(0, Math.min(score - 1, strengthColors.length - 1));
                 
                 if (strengthBar) {
                    strengthBar.style.width = password ? barWidths[level] : '0%';
                    strengthBar.style.backgroundColor = password ? strengthColors[level] : 'transparent';
                 }
             }

             if (newPassInput) {
                 newPassInput.addEventListener('input', function() {
                     checkPasswordStrength(this.value);
                 });
             }

             // Form submission handler
             if (passwordForm) {
                 passwordForm.addEventListener('submit', function(event) {
                     // Allow PHP to handle actual submission logic, but do basic client validation here
                     const oldPass = document.getElementById('oldpass').value;
                     const newPass = newPassInput.value;
                     const confPass = confPassInput.value;
                     
                     let isValid = true;
                     let errorMessage = '';

                     if (oldPass === '' || newPass === '' || confPass === '') {
                         isValid = false;
                         errorMessage = 'All password fields are required.';
                     } else if (newPass !== confPass) {
                         isValid = false;
                         errorMessage = 'New password and confirm password do not match.';
                     } else if (newPass.length < 8) {
                         isValid = false;
                         errorMessage = 'New password must be at least 8 characters long.';
                     }

                     if (!isValid) {
                         event.preventDefault(); // Stop form submission
                         Swal.fire({
                             title: 'Error!',
                             text: errorMessage,
                             icon: 'error',
                             confirmButtonText: 'OK',
                             confirmButtonColor: '#003399'
                         });
                     }
                 });
             }

             // Handle password visibility toggle for all password fields
             document.querySelectorAll('.toggle-icon').forEach(function(icon) {
                 icon.addEventListener('click', function() {
                     const container = this.closest('.password-container');
                     if (container) {
                         const input = container.querySelector('input');
                         const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
                         input.setAttribute('type', type);
                         this.classList.toggle('mdi-eye-outline');
                         this.classList.toggle('mdi-eye-off-outline');
                     }
                 });
             });

             // SweetAlert handler for server-side messages
             <?php if (!empty($message)): ?>
             Swal.fire({
                 title: '<?php echo $alertType === 'success' ? 'Successful!' : 'Error!'; ?>',
                 text: '<?php echo $message; ?>',
                 icon: '<?php echo $alertType; ?>',
                 confirmButtonText: 'OK',
                 confirmButtonColor: '#003399'
             }).then((result) => {
                 if (result.isConfirmed && '<?php echo $alertType; ?>' === 'success') {
                     window.location.href = 'password.php'; // Redirect to same page to clear POST
                 }
             });
             <?php endif; ?>
         });
      </script>
   </body>
</html>