<?php
session_start();
$db_path = file_exists('includes/db.php') ? 'includes/db.php' : '../includes/db.php';
if (file_exists($db_path)) {
    require $db_path;
} else {
    $conn = new mysqli('localhost', 'root', '', 'bajipari');
}

// Check Login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$msg = "";
$msg_type = "";

// Handle Password Change
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $current_pass = $_POST['current_password'];
    $new_pass = $_POST['new_password'];
    $confirm_pass = $_POST['confirm_password'];

    // Fetch User
    $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $user = $res->fetch_assoc();

    if ($user) {
        if (!password_verify($current_pass, $user['password'])) {
            $msg = "বর্তমান পাসওয়ার্ড ভুল!";
            $msg_type = "error";
        } elseif ($new_pass !== $confirm_pass) {
            $msg = "নতুন পাসওয়ার্ড মিলছে না!";
            $msg_type = "error";
        } elseif (strlen($new_pass) < 6 || strlen($new_pass) > 20) {
            $msg = "পাসওয়ার্ড ৬-২০ অক্ষরের মধ্যে হতে হবে।";
            $msg_type = "error";
        } else {
            // Update Password
            $new_hash = password_hash($new_pass, PASSWORD_BCRYPT);
            $update = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $update->bind_param("si", $new_hash, $user_id);
            
            if ($update->execute()) {
                $msg = "পাসওয়ার্ড সফলভাবে পরিবর্তন করা হয়েছে!";
                $msg_type = "success";
            } else {
                $msg = "ত্রুটি হয়েছে, আবার চেষ্টা করুন।";
                $msg_type = "error";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Change Password</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">

    <style>
        body { 
            background-color: #121619; 
            color: #d1d5db; 
            font-family: 'Roboto', sans-serif; 
            padding-bottom: 90px;
        }

        /* --- Header --- */
        .header-bg { 
            background-color: #232a31; 
            padding: 15px; 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            position: relative;
            border-bottom: 1px solid #2f3840;
        }
        .close-btn {
            position: absolute;
            right: 15px;
            font-size: 18px;
            color: #9ca3af;
        }

        /* --- Form Elements --- */
        .input-group {
            margin-bottom: 15px;
        }
        .input-label {
            font-size: 12px;
            color: #ffffff;
            margin-bottom: 8px;
            display: block;
        }
        .input-wrapper {
            position: relative;
            background-color: #2f3b43;
            border-radius: 4px;
            border: 1px solid #374151;
        }
        .custom-input {
            width: 100%;
            background: transparent;
            border: none;
            color: #9ca3af;
            padding: 12px 40px 12px 15px; /* Right padding for eye icon */
            font-size: 14px;
            outline: none;
        }
        .eye-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6b7280;
            cursor: pointer;
        }

        /* --- Validation List --- */
        .validation-list {
            margin-bottom: 20px;
        }
        .valid-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 12px;
            color: #6b7280; /* Default gray */
            margin-bottom: 5px;
            transition: color 0.3s;
        }
        .valid-item i {
            font-size: 14px;
        }
        .valid-item.success {
            color: #10b981; /* Green when valid */
        }

        /* --- Confirm Button --- */
        .btn-confirm {
            background-color: #eab308;
            color: #000;
            width: 100%;
            padding: 12px;
            border-radius: 4px;
            font-weight: bold;
            font-size: 14px;
            border: none;
            margin-top: 10px;
        }

        /* Bottom Nav */
        .bottom-nav { background-color: #000; border-top: 1px solid #222; }
        .nav-item { color: #6b7280; }
        .nav-item.active { color: #facc15; }
    </style>
</head>
<body>

    <div class="header-bg sticky top-0 z-50">
        <h1 class="text-white font-medium text-base">Change Password</h1>
        <a href="account.php" class="close-btn"><i class="fas fa-times"></i></a>
    </div>

    <?php if($msg): ?>
        <div class="px-4 mt-4">
            <div class="p-3 rounded text-center text-xs font-bold <?php echo $msg_type == 'success' ? 'bg-green-900/30 text-green-500' : 'bg-red-900/30 text-red-500'; ?>">
                <?php echo $msg; ?>
            </div>
        </div>
    <?php endif; ?>

    <div class="p-5">
        
        <form method="POST">
            
            <div class="input-group">
                <label class="input-label">Current password</label>
                <div class="input-wrapper">
                    <input type="password" name="current_password" id="currPass" class="custom-input" placeholder="Current password" required>
                    <i class="fas fa-eye-slash eye-icon" onclick="togglePass('currPass', this)"></i>
                </div>
            </div>

            <div class="input-group">
                <label class="input-label">New password</label>
                <div class="input-wrapper">
                    <input type="password" name="new_password" id="newPass" class="custom-input" placeholder="New password" required oninput="validatePassword(this.value)">
                    <i class="fas fa-eye-slash eye-icon" onclick="togglePass('newPass', this)"></i>
                </div>
            </div>

            <div class="validation-list">
                <div class="valid-item" id="rule-length">
                    <i class="fas fa-check-circle"></i> Between 6~20 characters.
                </div>
                <div class="valid-item" id="rule-alpha">
                    <i class="fas fa-check-circle"></i> At least one alphabet.
                </div>
                <div class="valid-item" id="rule-num">
                    <i class="fas fa-check-circle"></i> At least one number. (Special character, symbols are allowed)
                </div>
            </div>

            <div class="input-group">
                <label class="input-label">Confirm new password</label>
                <div class="input-wrapper">
                    <input type="password" name="confirm_password" id="confPass" class="custom-input" placeholder="Confirm new password" required>
                    <i class="fas fa-eye-slash eye-icon" onclick="togglePass('confPass', this)"></i>
                </div>
            </div>

            <button type="submit" class="btn-confirm">Confirm</button>

        </form>

    </div>

    <div class="fixed bottom-0 left-0 w-full h-[60px] bottom-nav z-50 flex justify-between items-center px-6">
        <a href="index.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-home text-lg mb-1"></i>
            <span class="text-[10px]">Home</span>
        </a>
        <a href="promotions.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-gift text-lg mb-1"></i>
            <span class="text-[10px]">Promotions</span>
        </a>
        <a href="deposit.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-wallet text-lg mb-1"></i>
            <span class="text-[10px]">Deposit</span>
        </a>
        <a href="account.php" class="flex flex-col items-center justify-center nav-item active">
            <i class="fas fa-user text-lg mb-1"></i>
            <span class="text-[10px]">My Account</span>
        </a>
    </div>

    <script>
        // Toggle Password Visibility
        function togglePass(inputId, icon) {
            const input = document.getElementById(inputId);
            if (input.type === "password") {
                input.type = "text";
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            } else {
                input.type = "password";
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            }
        }

        // Real-time Validation
        function validatePassword(val) {
            // Rule 1: Length 6-20
            const ruleLength = document.getElementById('rule-length');
            if (val.length >= 6 && val.length <= 20) {
                ruleLength.classList.add('success');
            } else {
                ruleLength.classList.remove('success');
            }

            // Rule 2: At least one alphabet
            const ruleAlpha = document.getElementById('rule-alpha');
            if (/[a-zA-Z]/.test(val)) {
                ruleAlpha.classList.add('success');
            } else {
                ruleAlpha.classList.remove('success');
            }

            // Rule 3: At least one number
            const ruleNum = document.getElementById('rule-num');
            if (/\d/.test(val)) {
                ruleNum.classList.add('success');
            } else {
                ruleNum.classList.remove('success');
            }
        }
    </script>

</body>
</html>