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

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

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

$message = '';
$alertType = '';

if (isset($_POST["button"])) {
    $hide_id = $_SESSION['customerid'];
    $oldpass = $_POST['oldpass'];
    $newpass = $_POST['newpass'];
    $confpass = $_POST['confpass'];

    // Input validation
    if (empty($oldpass) || empty($newpass) || empty($confpass)) {
        $message = 'All fields are required!';
        $alertType = 'error';
    } elseif ($newpass !== $confpass) {
        $message = 'New pin and confirm pin do not match!';
        $alertType = 'error';
    } else {
        // Use prepared statements for security
        $stmt = $con->prepare("SELECT transpassword FROM customers WHERE customerid = ? AND transpassword = ? LIMIT 1");
        $stmt->bind_param("is", $hide_id, $oldpass);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $stmt_update = $con->prepare("UPDATE customers SET transpassword = ? WHERE customerid = ?");
            $stmt_update->bind_param("si", $newpass, $hide_id);

            if ($stmt_update->execute()) {
                $message = 'Your new transaction pin has been updated successfully!';
                $alertType = 'success';
            } else {
                $message = 'Failed to update transaction pin. Please try again.';
                $alertType = 'error';
            }
            $stmt_update->close();
        } else {
            $message = 'The current transaction pin you entered is incorrect.';
            $alertType = 'error';
        }
        $stmt->close();
    }
}
?>

<html lang="en">
   <head>
      <meta charset="utf-8" />
      <title>Update Transaction Pin | <?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">
      
      <script src="assets/libs2/custom/sweetalert.min.js"></script>
      <style>
    /* --- PREMIUM BLUE THEME --- */
    :root {
        --primary-purple: #003399; /* Primary Blue */
        --dark-purple: #005D9D;    /* Secondary Blue */
        --soft-purple-bg: #e6efff; /* Light Blue background */
        --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; }

    .pin-header {
        text-align: center;
        margin-bottom: 30px;
    }
    
    .pin-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-meter-fill.weak { width: 25%; background-color: #ef4444; }
    .password-meter-fill.medium { width: 50%; background-color: #f59e0b; }
    .password-meter-fill.strong { width: 75%; background-color: #10b981; }
    .password-meter-fill.very-strong { width: 100%; background-color: #3b82f6; }
    
    .password-rules {
      list-style: none;
      padding: 0;
      margin-top: 15px;
      font-size: 12px;
      color: var(--text-secondary);
    }
    .password-rules li {
      display: flex;
      align-items: center;
      margin-bottom: 5px;
    }
    .password-rules .valid::before {
      content: '✔';
      color: #10b981;
      margin-right: 8px;
      font-weight: bold;
    }
    .password-rules .invalid::before {
      content: '✖';
      color: #ef4444;
      margin-right: 8px;
      font-weight: bold;
    }
    
    .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 .form-control {
        padding-right: 3rem; 
    }
    
    .password-container .toggle-icon {
        position: absolute;
        right: 1rem; 
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
        color: #94a3b8;
        font-size: 1.25rem;
        transition: color 0.2s;
    }
    .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;
        box-shadow: 0 4px 12px rgba(0, 51, 153, 0.3); /* Adjusted Shadow to Blue */
    }

    .btn-primary:hover {
        background-color: var(--dark-purple);
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(0, 51, 153, 0.4);
    }
    
    /* Breadcrumb color helper */
    .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">Manage your transaction security pin.</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">PIN</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="pin-header">
                                  <div class="pin-icon-bg">
                                      <i class="mdi mdi-shield-lock-outline"></i>
                                  </div>
                                  <h4 class="fw-bold mb-1 text-dark">Update Transaction Pin</h4>
                                  <p class="text-muted small">Keep your account safe with a strong PIN.</p>
                              </div>

                              <form id="pinForm" method="post" action="">
                                 
                                 <div class="mb-4">
                                    <label for="oldpass" class="form-label fw-bold text-secondary small text-uppercase">Current Transaction Pin</label>
                                    <div class="password-container">
                                       <input type="password" name="oldpass" size="35" class="form-control" id="oldpass" placeholder="Enter current PIN">
                                       <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 Transaction Pin</label>
                                    <div class="password-container">
                                       <input required name="newpass" type="password" id="newpass" class="form-control" placeholder="Create your new PIN">
                                       <i class="mdi mdi-eye-outline toggle-icon"></i>
                                    </div>
                                    
                                    <div class="password-meter">
                                       <div id="password-meter-fill" class="password-meter-fill"></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 Pin</label>
                                    <div class="password-container">
                                       <input class="form-control" required name="confpass" type="password" id="confpass" placeholder="Confirm new PIN">
                                       <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 Secure Pin <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="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/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 pinForm = document.getElementById('pinForm');
             const newPassInput = document.getElementById('newpass');
             const meterFill = document.getElementById('password-meter-fill');
             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 updatePasswordStrength() {
                 const password = newPassInput.value;
                 let strength = 0;

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

                 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) strength++;
                 if (hasUppercase) strength++;
                 if (hasNumber) strength++;
                 if (hasSpecial) strength++;

                 if (meterFill) {
                     meterFill.className = 'password-meter-fill';
                     if (strength === 1) meterFill.classList.add('weak');
                     if (strength === 2) meterFill.classList.add('medium');
                     if (strength === 3) meterFill.classList.add('strong');
                     if (strength === 4) meterFill.classList.add('very-strong');
                 }
             }

             if (newPassInput) {
                 newPassInput.addEventListener('input', updatePasswordStrength);
             }

             // Form submission handler
             if (pinForm) {
                 pinForm.addEventListener('submit', function(event) {
                     // We allow PHP to handle the submission, but we do client validation first
                     const oldPass = document.getElementById('oldpass').value;
                     const newPass = newPassInput.value;
                     const confPass = document.getElementById('confpass').value;

                     if (oldPass === '' || newPass === '' || confPass === '') {
                         event.preventDefault();
                         Swal.fire('Error!', 'All fields are required!', 'error');
                         return;
                     }
                     if (newPass !== confPass) {
                         event.preventDefault();
                         Swal.fire('Error!', 'New pin and confirm pin do not match!', 'error');
                         return;
                     }

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

                     if (!isLengthValid || !hasUppercase || !hasNumber || !hasSpecial) {
                         event.preventDefault();
                         Swal.fire('Error!', 'Your new pin is not strong enough. Please follow the rules listed below the field.', 'error');
                         return;
                     }
                 });
             }

             // 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 = 'pin.php';
                 }
             });
             <?php endif; ?>
         });
      </script>
   </body>
</html>