<?php
session_start();
include('conexion.php');

if (isset($_POST['login'])) {
    $usuario = trim((string)($_POST['usuario'] ?? ''));
    $contrasena = (string)($_POST['contrasena'] ?? '');
    $loginError = false;

    if ($usuario !== '' && $contrasena !== '') {
        $stmt = mysqli_prepare($conexion, "SELECT id, nombre, usuario, contrasena, rol FROM usuarios WHERE usuario = ? LIMIT 1");
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, 's', $usuario);
            mysqli_stmt_execute($stmt);
            $resultado = mysqli_stmt_get_result($stmt);
            $fila = $resultado ? mysqli_fetch_assoc($resultado) : null;
            mysqli_stmt_close($stmt);

            $passwordOk = false;
            if ($fila) {
                $hashInfo = password_get_info((string)$fila['contrasena']);
                if (!empty($hashInfo['algo'])) {
                    $passwordOk = password_verify($contrasena, (string)$fila['contrasena']);
                } else {
                    // Compatibilidad temporal: permite entrar con contraseñas antiguas en texto plano
                    // y las migra automáticamente a hash seguro en el primer inicio correcto.
                    $passwordOk = hash_equals((string)$fila['contrasena'], $contrasena);
                    if ($passwordOk) {
                        $nuevoHash = password_hash($contrasena, PASSWORD_DEFAULT);
                        $upd = mysqli_prepare($conexion, "UPDATE usuarios SET contrasena = ? WHERE id = ?");
                        if ($upd) {
                            $uid = (int)$fila['id'];
                            mysqli_stmt_bind_param($upd, 'si', $nuevoHash, $uid);
                            mysqli_stmt_execute($upd);
                            mysqli_stmt_close($upd);
                        }
                    }
                }
            }

            if ($passwordOk) {
                session_regenerate_id(true);
                $_SESSION['usuario'] = $fila['usuario'];
                $_SESSION['rol'] = $fila['rol'];
                header('Location: index.php');
                exit;
            }
        }
    }

    echo '<script type="text/javascript">
            alert("Credenciales incorrectas");
            window.location.href="login.php";
          </script>';
    exit;
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistema de Nómina - Login</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        :root {
            --primary-color: #1a3c8b;
            --secondary-color: #4CAF50;
            --accent-color: #FF9800;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
        }
        
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
        }
        
        .login-container {
            width: 100%;
            max-width: 450px;
            animation: fadeIn 0.8s ease-out;
        }
        
        .login-card {
            background-color: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            border: none;
        }
        
        .card-header {
            background: linear-gradient(to right, var(--primary-color), #2a4ca3);
            color: white;
            text-align: center;
            padding: 30px 20px;
            border-bottom: none;
        }
        
        .company-logo {
            width: 80px;
            height: 80px;
            background-color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }
        
        .company-logo img {
            max-width: 60px;
            max-height: 60px;
        }
        
        .company-name {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 5px;
            letter-spacing: 0.5px;
        }
        
        .system-name {
            font-size: 1.1rem;
            opacity: 0.9;
            margin-bottom: 5px;
        }
        
        .system-subtitle {
            font-size: 0.9rem;
            opacity: 0.7;
            font-weight: 300;
        }
        
        .card-body {
            padding: 30px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            font-weight: 600;
            color: var(--dark-color);
            margin-bottom: 8px;
            display: block;
        }
        
        .input-group {
            position: relative;
        }
        
        .input-group-prepend .input-group-text {
            background-color: #f1f5f9;
            border: 1px solid #dee2e6;
            border-right: none;
            color: var(--primary-color);
        }
        
        .form-control {
            border: 1px solid #dee2e6;
            padding: 12px 15px;
            border-radius: 8px;
            transition: all 0.3s;
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(26, 60, 139, 0.25);
        }
        
        .login-btn {
            background: linear-gradient(to right, var(--primary-color), #2a4ca3);
            border: none;
            color: white;
            padding: 12px;
            font-weight: 600;
            border-radius: 8px;
            width: 100%;
            margin-top: 10px;
            transition: all 0.3s;
            letter-spacing: 0.5px;
        }
        
        .login-btn:hover {
            background: linear-gradient(to right, #15326f, var(--primary-color));
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(26, 60, 139, 0.3);
        }
        
        .login-btn:active {
            transform: translateY(0);
        }
        
        .footer-info {
            text-align: center;
            margin-top: 25px;
            padding-top: 15px;
            border-top: 1px solid #eee;
            color: #666;
            font-size: 0.85rem;
        }
        
        .footer-info i {
            color: var(--secondary-color);
            margin-right: 5px;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @media (max-width: 576px) {
            .login-container {
                padding: 10px;
            }
            
            .card-body {
                padding: 20px;
            }
        }
        
        .placeholder-logo {
            font-size: 2rem;
            color: var(--primary-color);
        }
        
        .security-notice {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 12px;
            margin-top: 20px;
            font-size: 0.85rem;
            color: #666;
            border-left: 4px solid var(--secondary-color);
        }
        
        .security-notice i {
            color: var(--secondary-color);
            margin-right: 8px;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="card-header">
                <div class="company-logo">
                    <!-- Reemplaza esta parte con tu logo real -->
                    <div class="placeholder-logo">
					<img src="image/logo.png" alt="Logo" class="logo"> 
                        <i class="fas fa-building"></i>
                    </div>
                    <!-- Si tienes un logo, usa esta línea: -->
                    <!-- <img src="image/logo_distribuidora.png" alt="Logo Distribuidora Riga0803 C.A."> -->
                </div>
                <div class="company-name">Distribuidora Riga0803 C.A.</div>
                <div class="system-name">Sistema de Nómina</div>
                <div class="system-subtitle">Gestión de Nómina y Recursos Humanos</div>
            </div>
            
            <div class="card-body">
                <form action="login.php" method="post">
                    <div class="form-group">
                        <label for="usuario">Usuario</label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><i class="fas fa-user"></i></span>
                            </div>
                            <input type="text" id="usuario" name="usuario" class="form-control" placeholder="Ingrese su usuario" required autofocus>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="contrasena">Contraseña</label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><i class="fas fa-lock"></i></span>
                            </div>
                            <input type="password" id="contrasena" name="contrasena" class="form-control" placeholder="Ingrese su contraseña" required>
                        </div>
                    </div>
                    
                    <button type="submit" name="login" class="btn login-btn">
                        <i class="fas fa-sign-in-alt"></i> Iniciar Sesión
                    </button>
                    
                    <div class="security-notice">
                        <i class="fas fa-shield-alt"></i> Este sistema contiene información confidencial. Acceso autorizado únicamente.
                    </div>
                </form>
                
                <div class="footer-info">
                    <div><i class="fas fa-info-circle"></i> Para asistencia, contacte al departamento de Sistemas</div>
                    <div class="mt-2"><i class="far fa-copyright"></i> <?php echo date('Y'); ?> Distribuidora Riga0803 C.A.</div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>