<?php
require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';

// Generisanje CSRF tokena za zaštitu forme
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$error = '';
$success = '';
$token = isset($_GET['token']) ? $_GET['token'] : '';
$valid_token = false;
$user_id = 0;

// Validacija tokena
if (!empty($token)) {
    $user = get_row("
        SELECT id FROM users 
        WHERE reset_token = ? AND reset_expires > NOW() AND role = 'admin'
    ", [$token]);
    
    if ($user) {
        $valid_token = true;
        $user_id = $user['id'];
    } else {
        $error = 'Nevažeći ili istekao token za resetovanje lozinke.';
    }
} else {
    $error = 'Nedostaje token za resetovanje lozinke.';
}

// Obrada forme za resetovanje lozinke
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $valid_token) {
    // Provera CSRF tokena
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error = 'Nevažeća forma. Molimo pokušajte ponovo.';
    } else {
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        $confirm_password = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : '';
        
        // Validacija
        if (empty($password)) {
            $error = 'Molimo unesite novu lozinku.';
        } elseif (strlen($password) < 8) {
            $error = 'Lozinka mora imati najmanje 8 karaktera.';
        } elseif ($password !== $confirm_password) {
            $error = 'Lozinke se ne podudaraju.';
        } else {
            // Hash lozinke
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            // Ažuriranje lozinke i čišćenje tokena
            execute_query("
                UPDATE users 
                SET password = ?, reset_token = NULL, reset_expires = NULL 
                WHERE id = ?
            ", [$hashed_password, $user_id]);
            
            $success = 'Lozinka je uspešno promenjena. Možete se prijaviti sa novom lozinkom.';
        }
    }
    
    // Regenerisanje CSRF tokena nakon slanja forme
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>
<!DOCTYPE html>
<html lang="sr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Resetovanje lozinke | <?php echo get_setting('site_name', 'Hugong Aparati'); ?></title>
    
    <!-- Google Font: Source Sans Pro -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="/admin/assets/css/adminlte.min.css">
    
    <!-- Favicon -->
    <link rel="icon" href="/favicon.ico">
    <link rel="apple-touch-icon" href="/apple-touch-icon.png">
    
    <style>
        .login-page {
            min-height: 100vh;
            background: linear-gradient(135deg, #0077cc 0%, #005fa3 100%);
        }
        .login-box {
            width: 400px;
            max-width: 90%;
        }
        .login-logo {
            margin-bottom: 1.5rem;
        }
        .login-logo img {
            max-height: 60px;
            margin-bottom: 10px;
        }
        .login-logo a {
            color: #fff;
            font-weight: 300;
        }
        .card {
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: none;
        }
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            padding: 1.25rem;
            border-radius: 10px 10px 0 0 !important;
        }
        .card-body {
            padding: 1.5rem;
        }
        .btn-primary {
            background-color: #0077cc;
            border-color: #0077cc;
        }
        .btn-primary:hover {
            background-color: #005fa3;
            border-color: #005fa3;
        }
        .form-control {
            height: calc(2.5rem + 2px);
        }
        .input-group-text {
            background-color: transparent;
        }
        .login-box-msg {
            color: #6c757d;
            font-size: 0.9rem;
        }
        .alert {
            border-radius: 5px;
        }
        .login-footer {
            margin-top: 2rem;
            text-align: center;
            color: rgba(255,255,255,0.8);
            font-size: 0.85rem;
        }
        .login-footer a {
            color: #fff;
        }
        .password-strength {
            height: 5px;
            margin-top: 5px;
            border-radius: 5px;
            background-color: #e9ecef;
        }
        .password-strength div {
            height: 100%;
            border-radius: 5px;
            transition: width 0.3s ease;
        }
        .password-strength-text {
            font-size: 12px;
            margin-top: 5px;
        }
        .input-group-text.toggle-password {
            cursor: pointer;
        }
    </style>
</head>
<body class="login-page">
    <div class="login-box">
        <div class="login-logo">
            <img src="/assets/images/logo.png" alt="<?php echo get_setting('site_name', 'Hugong Aparati'); ?>" class="img-fluid">
            <a href="/admin/"><b>Admin</b> Panel</a>
        </div>
        
        <div class="card">
            <div class="card-header text-center">
                <h4 class="mb-0">Resetovanje lozinke</h4>
            </div>
            <div class="card-body">
                <?php if (!empty($error)): ?>
                <div class="alert alert-danger alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <i class="icon fas fa-ban"></i> <?php echo $error; ?>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($success)): ?>
                <div class="alert alert-success alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <i class="icon fas fa-check"></i> <?php echo $success; ?>
                </div>
                <div class="text-center mt-4">
                    <a href="/admin/login.php" class="btn btn-primary">Idi na prijavu</a>
                </div>
                <?php elseif ($valid_token): ?>
                <p class="login-box-msg">Unesite novu lozinku</p>
                
                <form action="" method="post" id="reset-form">
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    
                    <div class="input-group mb-1">
                        <input type="password" class="form-control" id="password" name="password" placeholder="Nova lozinka" minlength="8" required>
                        <div class="input-group-append">
                            <div class="input-group-text toggle-password" toggle="#password">
                                <span class="fas fa-eye"></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="password-strength">
                        <div id="password-strength-meter"></div>
                    </div>
                    <div class="password-strength-text mb-3" id="password-strength-text"></div>
                    
                    <div class="input-group mb-3">
                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Potvrdite novu lozinku" required>
                        <div class="input-group-append">
                            <div class="input-group-text toggle-password" toggle="#confirm_password">
                                <span class="fas fa-eye"></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary btn-block">Promeni lozinku</button>
                        </div>
                    </div>
                </form>
                <?php else: ?>
                <div class="text-center">
                    <p>Link za resetovanje lozinke je nevažeći ili je istekao.</p>
                    <a href="/admin/forgot-password.php" class="btn btn-primary mt-3">Zatraži novi link</a>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="login-footer">
            <p>&copy; <?php echo date('Y'); ?> <?php echo get_setting('site_name', 'Hugong Aparati'); ?>. Sva prava zadržana.</p>
            <p><a href="/">Nazad na sajt</a></p>
        </div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Bootstrap 4 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- AdminLTE App -->
    <script src="/admin/assets/js/adminlte.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Auto-close alert after 5 seconds
        setTimeout(function() {
            $('.alert').fadeOut('slow');
        }, 5000);
        
        // Show/hide password
        $('.toggle-password').click(function() {
            var input = $($(this).attr('toggle'));
            if (input.attr('type') === 'password') {
                input.attr('type', 'text');
                $(this).html('<span class="fas fa-eye-slash"></span>');
            } else {
                input.attr('type', 'password');
                $(this).html('<span class="fas fa-eye"></span>');
            }
        });
        
        // Password validation
        $('#password').on('keyup', function() {
            var password = $(this).val();
            var strength = 0;
            
            // Check length
            if (password.length >= 8) {
                strength += 25;
            }
            
            // Check lowercase and uppercase
            if (password.match(/[a-z]/) && password.match(/[A-Z]/)) {
                strength += 25;
            }
            
            // Check numbers
            if (password.match(/\d/)) {
                strength += 25;
            }
            
            // Check special characters
            if (password.match(/[^a-zA-Z0-9]/)) {
                strength += 25;
            }
            
            var color;
            var text;
            
            if (strength <= 25) {
                color = '#dc3545'; // danger
                text = 'Veoma slaba';
            } else if (strength <= 50) {
                color = '#ffc107'; // warning
                text = 'Slaba';
            } else if (strength <= 75) {
                color = '#28a745'; // success
                text = 'Dobra';
            } else {
                color = '#28a745'; // success
                text = 'Jaka';
            }
            
            $('#password-strength-meter').css({
                'width': strength + '%',
                'background-color': color
            });
            
            $('#password-strength-text').text('Jačina lozinke: ' + text);
            $('#password-strength-text').css('color', color);
        });
        
        // Confirm password validation
        $('#reset-form').on('submit', function(e) {
            var password = $('#password').val();
            var confirmPassword = $('#confirm_password').val();
            
            if (password !== confirmPassword) {
                e.preventDefault();
                alert('Lozinke se ne podudaraju!');
            }
        });
    });
    </script>
</body>
</html>