<?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 = '';

// Obrada forme za resetovanje lozinke
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Provera CSRF tokena
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error = 'Nevažeća forma. Molimo pokušajte ponovo.';
    } else {
        $email = isset($_POST['email']) ? trim($_POST['email']) : '';
        
        // Validacija
        if (empty($email)) {
            $error = 'Molimo unesite email adresu.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Molimo unesite ispravnu email adresu.';
        } else {
            // Provera korisnika u bazi
            $user = get_row("SELECT * FROM users WHERE email = ? AND role = 'admin'", [$email]);
            
            if ($user) {
                // Generisanje tokena za resetovanje lozinke
                $token = bin2hex(random_bytes(32));
                $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
                
                // Čuvanje tokena u bazi
                execute_query("UPDATE users SET reset_token = ?, reset_expires = ? WHERE id = ?", 
                    [$token, $expires, $user['id']]);
                
                // Slanje email-a sa linkom za resetovanje lozinke
                $reset_link = SITE_URL . '/admin/reset-password.php?token=' . $token;
                
                // Ovde bi trebalo da postoji kod za slanje email-a
                // Za demonstraciju, prikazuje se link direktno
                $success = 'Poslali smo vam email sa linkom za resetovanje lozinke. Link ističe za jedan sat.';
                
                // Prikazivanje linka za razvoj - u produkciji ukloniti ovo
                if (defined('DEVELOPMENT_MODE') && DEVELOPMENT_MODE) {
                    $success .= '<br><br>Link za resetovanje (samo za razvoj): <a href="' . $reset_link . '">' . $reset_link . '</a>';
                }
            } else {
                // Iz sigurnosnih razloga ne otkrivamo da li korisnik postoji
                $success = 'Ako email adresa postoji u našem sistemu, poslaćemo vam uputstva za resetovanje lozinke.';
            }
        }
    }
    
    // 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>Zaboravljena lozinka | <?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;
        }
    </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">Zaboravljena lozinka</h4>
            </div>
            <div class="card-body">
                <p class="login-box-msg">Unesite vašu email adresu za resetovanje lozinke</p>
                
                <?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>
                <?php endif; ?>
                
                <form action="" method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    
                    <div class="input-group mb-3">
                        <input type="email" class="form-control" name="email" placeholder="Email" required autofocus>
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span class="fas fa-envelope"></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary btn-block">Pošalji link za resetovanje</button>
                        </div>
                    </div>
                </form>
                
                <p class="mt-3 text-center">
                    <a href="/admin/login.php">Nazad na prijavu</a>
                </p>
            </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 7 seconds (longer for success message)
        setTimeout(function() {
            $('.alert').fadeOut('slow');
        }, 7000);
    });
    </script>
</body>
</html>