<?php
session_start();

// Sertakan file koneksi database
include_once '../api/db_connect.php'; 

// Periksa apakah pengguna sudah login sebagai jejaring
if (!isset($_SESSION['jejaring_logged_in']) || !$_SESSION['jejaring_logged_in']) {
    header('Location: ../auth/jejaring_login.php'); 
    exit();
}

$loggedInUsername = htmlspecialchars($_SESSION['jejaring_username']);
$loggedInNamaInstansi = htmlspecialchars($_SESSION['jejaring_nama_instansi']);
$message = '';
$message_type = ''; // 'success' atau 'error'

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $old_password = $_POST['old_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    // Validasi input di sisi server
    if (empty($old_password) || empty($new_password) || empty($confirm_password)) {
        $message = "Semua kolom wajib diisi!";
        $message_type = 'error';
    } elseif ($new_password !== $confirm_password) {
        $message = "Kata sandi baru dan konfirmasi tidak cocok.";
        $message_type = 'error';
    } elseif (strlen($new_password) < 8) {
        $message = "Kata sandi minimal 8 karakter.";
        $message_type = 'error';
    } elseif (!preg_match('/[A-Z]/', $new_password)) {
        $message = "Kata sandi harus mengandung setidaknya satu huruf besar.";
        $message_type = 'error';
    } elseif (!preg_match('/[^a-zA-Z0-9]/', $new_password)) {
        $message = "Kata sandi harus mengandung setidaknya satu simbol (contoh: !, @, #, $).";
        $message_type = 'error';
    } else {
        try {
            // Ambil hash kata sandi lama dari database
            $query = "SELECT password_hash FROM jejaring_users WHERE username = :username";
            $stmt = $pdo->prepare($query);
            $stmt->bindParam(':username', $loggedInUsername, PDO::PARAM_STR);
            $stmt->execute();
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && password_verify($old_password, $user['password_hash'])) {
                // Verifikasi kata sandi lama berhasil, buat hash baru untuk kata sandi baru
                $newPasswordHash = password_hash($new_password, PASSWORD_DEFAULT);
                
                // Update kata sandi di database
                $updateQuery = "UPDATE jejaring_users SET password_hash = :new_password_hash WHERE username = :username";
                $updateStmt = $pdo->prepare($updateQuery);
                $updateStmt->bindParam(':new_password_hash', $newPasswordHash, PDO::PARAM_STR);
                $updateStmt->bindParam(':username', $loggedInUsername, PDO::PARAM_STR);
                $updateStmt->execute();

                $message = "Kata sandi berhasil diubah!";
                $message_type = 'success';
            } else {
                $message = "Kata sandi lama salah. Mohon periksa kembali.";
                $message_type = 'error';
            }
        } catch (PDOException $e) {
            $message = "Terjadi kesalahan saat mengubah kata sandi: " . $e->getMessage();
            $message_type = 'error';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ubah Kata Sandi - RekamSehat</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        :root {
            --primary-color: #4dab25;
            --secondary-color: #024d52;
            --bg-light: #f4f7f6;
            --text-dark: #333;
            --text-light: #fefefe;
            --border-color: #e0e0e0;
            --sidebar-width: 250px;
            --header-height: 60px;
        }
        body {
            font-family: 'Poppins', sans-serif;
            margin: 0;
            background-color: var(--bg-light);
            color: var(--text-dark);
            display: flex;
            min-height: 100vh;
            overflow-x: hidden;
        }
        .header {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: var(--header-height);
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            padding: 0 0px;
            z-index: 1000;
            transition: margin-left 0.3s ease;
        }
        .header .logo {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--secondary-color);
            margin-right: auto;
        }
        .header .user-info {
            display: flex;
            align-items: center;
            font-size: 0.9rem;
            color: var(--text-dark);
        }
        .header .user-info .user-icon {
            margin-right: 8px;
            color: var(--primary-color);
        }
        .header .user-info .username {
            font-weight: 600;
            margin-right: 15px;
        }
        .header .logout-btn {
            background: none;
            border: none;
            color: var(--secondary-color);
            cursor: pointer;
            font-size: 1rem;
            padding: 5px 10px;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }
        .header .logout-btn:hover {
            background-color: rgba(0,0,0,0.05);
        }
        .sidebar {
            width: var(--sidebar-width);
            background: var(--secondary-color);
            color: var(--text-light);
            padding-top: var(--header-height);
            position: fixed;
            top: 0;
            left: 0;
            height: 100%;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            z-index: 999;
            transition: transform 0.3s ease;
            transform: translateX(0);
            overflow-y: auto;
        }
        .sidebar.hidden {
            transform: translateX(calc(-1 * var(--sidebar-width)));
        }
        .sidebar-header {
            padding: 20px;
            text-align: center;
            background-color: var(--primary-color);
            color: var(--text-light);
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .sidebar ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .sidebar ul li a {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            color: var(--text-light);
            text-decoration: none;
            font-size: 1rem;
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        .sidebar ul li a i {
            margin-right: 10px;
            font-size: 1.2rem;
        }
        .sidebar ul li a:hover,
        .sidebar ul li a.active {
            background-color: rgba(255, 255, 255, 0.2);
            color: #fff;
        }
        .sidebar .dropdown-btn {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px 20px;
            color: var(--text-light);
            text-decoration: none;
            font-size: 1rem;
            transition: background-color 0.3s ease, color 0.3s ease;
            cursor: pointer;
        }
        .sidebar .dropdown-btn i {
            margin-right: 10px;
            font-size: 1.2rem;
        }
        .sidebar .dropdown-btn:hover,
        .sidebar .dropdown-btn.active {
            background-color: rgba(255, 255, 255, 0.2);
            color: #fff;
        }
        .sidebar .dropdown-container {
            display: none;
            background-color: rgba(0, 0, 0, 0.1);
            padding-left: 20px;
        }
        .sidebar .dropdown-container a {
            padding: 12px 16px;
            text-decoration: none;
            color: var(--text-light);
            display: block;
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        .sidebar .dropdown-container a:hover {
            background-color: rgba(255, 255, 255, 0.2);
            color: #fff;
        }
        .sidebar .dropdown-container.show {
            display: block;
        }
        .main-content {
            margin-left: var(--sidebar-width);
            padding: calc(var(--header-height) + 30px) 30px 30px 30px;
            flex-grow: 1;
            transition: margin-left 0.3s ease;
            width: calc(100% - var(--sidebar-width));
        }
        .main-content.full-width {
            margin-left: 0;
            width: 100%;
        }
        .sidebar-toggle {
            position: fixed;
            top: 15px;
            left: calc(var(--sidebar-width) + 15px);
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 5px;
            padding: 8px 12px;
            cursor: pointer;
            z-index: 1001;
            transition: left 0.3s ease;
            font-size: 1.2rem;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .sidebar-toggle.shifted {
            left: 15px;
        }
        .sidebar-toggle:hover {
            background-color: #3e8d22;
        }
        .form-container {
            max-width: 500px;
            padding: 20px 0;
        }
        .form-container h2 {
            text-align: left;
            margin-bottom: 20px;
            color: var(--secondary-color);
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }
        .form-input-group {
            display: flex;
            align-items: center;
        }
        .form-input-group input {
            flex-grow: 1;
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 5px;
            font-family: inherit;
            font-size: 1rem;
        }
        .form-group label .required-symbol {
            color: red;
        }
        .form-group small {
            font-size: 0.8rem;
            color: #777;
            display: block;
            margin-top: 5px;
        }
        .submit-btn {
            width: 100%;
            padding: 12px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .submit-btn:hover {
            background-color: #3e8d22;
        }
        .message {
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 5px;
            text-align: center;
        }
        .message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .password-requirements {
            margin-top: 5px;
            list-style: none;
            padding: 0;
            font-size: 0.8rem;
            color: #555;
        }
        .password-requirements li {
            margin-bottom: 3px;
        }
        .password-requirements .invalid {
            color: red;
        }
        .password-requirements .valid {
            color: green;
        }
        .valid-icon {
            font-size: 1.5rem;
            color: green;
            margin-left: 10px;
            display: none;
        }
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(calc(-1 * var(--sidebar-width)));
                box-shadow: none;
            }
            .sidebar.show {
                transform: translateX(0);
            }
            .main-content {
                margin-left: 0;
                width: 100%;
                padding: calc(var(--header-height) + 20px) 20px 20px 20px;
            }
            .main-content.full-width {
                margin-left: 0;
            }
            .sidebar-toggle {
                left: 15px;
            }
            .sidebar-toggle.shifted {
                left: calc(var(--sidebar-width) + 15px);
            }
        }
        @media (max-width: 500px) {
            .header {
                padding: 0 10px;
            }
            .header .logo {
                font-size: 1.3rem;
            }
            .header .user-info {
                font-size: 0.8rem;
            }
            .header .logout-btn {
                font-size: 0.9rem;
                padding: 3px 8px;
            }
            .main-content {
                padding: calc(var(--header-height) + 15px) 15px 15px 15px;
            }
            .form-container {
                margin: 20px auto;
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <button class="sidebar-toggle" id="sidebarToggle">
            <i class="fas fa-bars"></i>
        </button>
        <div class="logo"></div>
        <div class="user-info">
            <span class="username"><i class="fas fa-user-circle user-icon"></i> <?php echo $loggedInNamaInstansi; ?></span>
            <a href="jejaring_logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            Menu Jejaring
        </div>
            <ul>
                <li><a href="../jejaring/"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
                <li><a href="change_password.php" class="active"><i class="fas fa-key"></i> Ubah Kata Sandi</a></li>
                <li>
                    <a href="#" class="dropdown-btn active">
                        <i class="fas fa-file-alt"></i> Laporan
                        <i class="fas fa-caret-down"></i>
                    </a>
                    <div class="dropdown-container show">
                        <a href="kehamilan/"><i class="fas fa-baby"></i> Laporan Kehamilan</a>
                        <a href="ptm_entry.php"><i class="fas fa-heartbeat"></i> Laporan PTM</a>
                        <a href="tb_entry.php"><i class="fas fa-lungs"></i> Entri Terduga TB</a>
                        <a href="kb_entry.php"><i class="fas fa-restroom"></i> Entri KB</a>
                    </div>
                </li>
            </ul>
    </aside>
    <main class="main-content" id="mainContent">
        <div class="form-container">
            <h2>Ubah Kata Sandi</h2>
            <?php if ($message): ?>
                <div class="message <?php echo $message_type; ?>">
                    <?php echo $message; ?>
                </div>
            <?php endif; ?>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                <div class="form-group">
                    <label for="old_password">Kata Sandi Lama<span class="required-symbol">*</span></label>
                    <div class="form-input-group">
                        <input type="password" id="old_password" name="old_password" required>
                    </div>
                </div>
                <div class="form-group">
                    <label for="new_password">Kata Sandi Baru<span class="required-symbol">*</span></label>
                    <div class="form-input-group">
                        <input type="password" id="new_password" name="new_password" required>
                        <i class="fas fa-check valid-icon" id="new-password-icon"></i>
                    </div>
                    <ul class="password-requirements">
                        <li id="req-length">Minimal 8 karakter</li>
                        <li id="req-uppercase">Mengandung setidaknya 1 huruf besar</li>
                        <li id="req-symbol">Mengandung setidaknya 1 simbol (contoh: !, @, #)</li>
                    </ul>
                </div>
                <div class="form-group">
                    <label for="confirm_password">Ulangi Kata Sandi Baru<span class="required-symbol">*</span></label>
                    <div class="form-input-group">
                        <input type="password" id="confirm_password" name="confirm_password" required>
                        <i class="fas fa-check valid-icon" id="confirm-password-icon"></i>
                    </div>
                </div>
                <button type="submit" class="submit-btn">Ubah Kata Sandi</button>
            </form>
        </div>
    </main>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const sidebarToggle = document.getElementById('sidebarToggle');
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.getElementById('mainContent');
            const dropdownBtn = document.querySelector('.dropdown-btn');
            const dropdownContainer = document.querySelector('.dropdown-container');

            function checkSidebarVisibility() {
                if (window.innerWidth <= 768) {
                    sidebar.classList.add('hidden');
                    mainContent.classList.add('full-width');
                    sidebarToggle.classList.add('shifted');
                } else {
                    sidebar.classList.remove('hidden');
                    mainContent.classList.remove('full-width');
                    sidebarToggle.classList.remove('shifted');
                }
            }
            checkSidebarVisibility();
            window.addEventListener('resize', checkSidebarVisibility);

            sidebarToggle.addEventListener('click', function() {
                sidebar.classList.toggle('hidden');
                mainContent.classList.toggle('full-width');
                sidebarToggle.classList.toggle('shifted');
            });

            const sidebarLinks = document.querySelectorAll('.sidebar ul li a');
            sidebarLinks.forEach(link => {
                link.addEventListener('click', function() {
                    if (window.innerWidth <= 768) {
                        sidebar.classList.add('hidden');
                        mainContent.classList.add('full-width');
                        sidebarToggle.classList.add('shifted');
                    }
                });
            });

            if(dropdownBtn){
                dropdownBtn.addEventListener('click', function() {
                    this.classList.toggle('active');
                    dropdownContainer.classList.toggle('show');
                });
            }

            // --- Logika validasi kata sandi di sisi klien ---
            const newPasswordInput = document.getElementById('new_password');
            const confirmPasswordInput = document.getElementById('confirm_password');
            const newPasswordIcon = document.getElementById('new-password-icon');
            const confirmPasswordIcon = document.getElementById('confirm-password-icon');
            const reqLength = document.getElementById('req-length');
            const reqUppercase = document.getElementById('req-uppercase');
            const reqSymbol = document.getElementById('req-symbol');

            function checkPasswordRequirements() {
                const password = newPasswordInput.value;
                let isValid = true;
                
                if (password.length >= 8) {
                    reqLength.className = 'valid';
                } else {
                    reqLength.className = 'invalid';
                    isValid = false;
                }

                if (/[A-Z]/.test(password)) {
                    reqUppercase.className = 'valid';
                } else {
                    reqUppercase.className = 'invalid';
                    isValid = false;
                }

                if (/[^a-zA-Z0-9]/.test(password)) {
                    reqSymbol.className = 'valid';
                } else {
                    reqSymbol.className = 'invalid';
                    isValid = false;
                }

                if (isValid) {
                    newPasswordIcon.style.display = 'inline-block';
                } else {
                    newPasswordIcon.style.display = 'none';
                }
            }

            function checkPasswordMatch() {
                const newPassword = newPasswordInput.value;
                const confirmPassword = confirmPasswordInput.value;
                const requirementsMet = newPasswordIcon.style.display === 'inline-block';

                if (requirementsMet && newPassword.length > 0 && confirmPassword.length > 0 && newPassword === confirmPassword) {
                    confirmPasswordIcon.style.display = 'inline-block';
                } else {
                    confirmPasswordIcon.style.display = 'none';
                }
            }

            newPasswordInput.addEventListener('keyup', () => {
                checkPasswordRequirements();
                checkPasswordMatch();
            });
            confirmPasswordInput.addEventListener('keyup', checkPasswordMatch);
        });
    </script>
</body>
</html>