<?php
/* ====================================================
SAFETY TALK SYSTEM - PT CITRA LAMPIA MANDIRI
File        : login.php
Versi       : 1.0 (CSV-Based Authentication)
Fitur       : - Autentikasi via CSV di /users/
              - Session Management (Asia/Jakarta)
              - Role-Based Redirect (Admin/Petugas)
              - UI Profesional dengan Animasi
              - Validasi Client + Server Side
====================================================
*/

// Set timezone & start session
date_default_timezone_set('Asia/Jakarta');
if(session_status() === PHP_SESSION_NONE) session_start();

// Redirect if already logged in
if(isset($_SESSION['user_logged_in']) && $_SESSION['user_logged_in'] === true) {
    header('Location: index.php');
    exit;
}

$error = '';
$success = '';
$oldNama = '';

// Handle Login Submission
if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nama = trim($_POST['nama'] ?? '');
    $password = $_POST['password'] ?? '';
    $remember = isset($_POST['remember']);
    
    $oldNama = $nama; // Preserve input for UX
    
    if(empty($nama) || empty($password)) {
        $error = '⚠️ Nama dan password wajib diisi!';
    } else {
        $csvPath = __DIR__ . '/users/users.csv';
        $authenticated = false;
        $userData = null;
        
        if(file_exists($csvPath)) {
            $file = fopen($csvPath, 'r');
            $header = fgetcsv($file); // Skip header row
            
            while(($row = fgetcsv($file)) !== FALSE) {
                if(count($row) >= 4) {
                    $csvNama = trim($row[0] ?? '');
                    $csvNik = trim($row[1] ?? '');
                    $csvRoles = trim($row[2] ?? '');
                    $csvPassword = trim($row[3] ?? '');
                    
                    // Simple authentication (plain text for CSV demo)
                    if(strtolower($csvNama) === strtolower($nama) && $csvPassword === $password) {
                        $authenticated = true;
                        $userData = [
                            'nama' => $csvNama,
                            'nik' => $csvNik,
                            'roles' => $csvRoles,
                            'login_time' => date('Y-m-d H:i:s')
                        ];
                        break;
                    }
                }
            }
            fclose($file);
        }
        
        if($authenticated && $userData) {
            // Set session variables
            $_SESSION['user_logged_in'] = true;
            $_SESSION['user_name'] = $userData['nama'];
            $_SESSION['user_nik'] = $userData['nik'];
            $_SESSION['user_role'] = $userData['roles'];
            $_SESSION['login_time'] = $userData['login_time'];
            $_SESSION['last_activity'] = time();
            
            // Remember me (optional, 30 days cookie)
            if($remember) {
                setcookie('remember_nama', $userData['nama'], time() + (86400 * 30), '/', '', false, true);
            }
            
            $success = '✅ Login berhasil! Mengalihkan...';
            
            // Redirect based on role
            header('Refresh: 1.5; url=index.php');
        } else {
            $error = '❌ Nama atau password tidak sesuai!';
        }
    }
}

// Check for remember me cookie (auto-fill)
if(empty($oldNama) && isset($_COOKIE['remember_nama'])) {
    $oldNama = htmlspecialchars($_COOKIE['remember_nama']);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login | Safety Talk System - PT CLM</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="icon" type="image/x-icon" href="assets/img/clm_logo3.png">
    <style>
        :root {
            --primary: #0f172a; --primary-dark: #1e3a8a; --primary-light: #3b82f6;
            --accent: #2563eb; --success: #059669; --warning: #f59e0b; --danger: #dc2626;
            --gray-50: #f8fafc; --gray-100: #f1f5f9; --gray-200: #e2e8f0; --gray-300: #cbd5e1;
            --gray-500: #64748b; --gray-700: #334155; --gray-900: #0f172a;
            --shadow-sm: 0 1px 2px rgba(0,0,0,0.05); --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1);
            --shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1); --radius: 8px; --radius-lg: 12px;
            --transition: all 0.2s ease;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: linear-gradient(135deg, var(--gray-100) 0%, var(--gray-50) 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            color: var(--gray-900);
        }
        
        /* Login Container */
        .login-wrapper {
            width: 100%;
            max-width: 420px;
            animation: slideUp 0.4s ease;
        }
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* Brand Header */
        .login-brand {
            text-align: center;
            margin-bottom: 24px;
        }
        .brand-logo {
            width: 70px;
            height: 70px;
            background: linear-gradient(135deg, white);
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 16px;
            box-shadow: var(--shadow-md);
        }
        .brand-logo i {
            font-size: 32px;
            color: white;
        }
        .brand-name {
            font-size: 18px;
            font-weight: 700;
            color: var(--gray-900);
            margin-bottom: 4px;
        }
        .brand-subtitle {
            font-size: 12px;
            color: var(--gray-500);
        }
        
        /* Login Card */
        .login-card {
            background: white;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--gray-200);
            overflow: hidden;
        }
        .login-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            color: white;
            padding: 20px 24px;
            text-align: center;
        }
        .login-header h2 {
            font-size: 16px;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        .login-header p {
            font-size: 11px;
            opacity: 0.9;
            margin-top: 4px;
        }
        .login-body {
            padding: 24px;
        }
        
        /* Alert Messages */
        .alert {
            padding: 12px 16px;
            border-radius: var(--radius);
            font-size: 13px;
            margin-bottom: 16px;
            display: flex;
            align-items: flex-start;
            gap: 10px;
            animation: fadeIn 0.3s ease;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .alert-error {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #b91c1c;
        }
        .alert-success {
            background: #ecfdf5;
            border: 1px solid #6ee7b7;
            color: #065f46;
        }
        .alert i { margin-top: 2px; font-size: 14px; }
        
        /* Form Groups */
        .form-group {
            margin-bottom: 16px;
        }
        .form-group label {
            display: block;
            font-size: 12px;
            font-weight: 600;
            color: var(--gray-700);
            text-transform: uppercase;
            letter-spacing: 0.3px;
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .form-group label i { color: var(--accent); font-size: 10px; }
        .form-control {
            width: 100%;
            padding: 12px 14px;
            border: 1px solid var(--gray-300);
            border-radius: var(--radius);
            font-size: 14px;
            background: var(--gray-50);
            transition: var(--transition);
        }
        .form-control:focus {
            outline: none;
            border-color: var(--accent);
            background: white;
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }
        .form-control::placeholder { color: var(--gray-400); }
        
        /* Password Toggle */
        .password-wrapper {
            position: relative;
        }
        .password-toggle {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: var(--gray-500);
            cursor: pointer;
            padding: 4px;
            font-size: 14px;
            transition: var(--transition);
        }
        .password-toggle:hover { color: var(--accent); }
        
        /* Remember & Forgot */
        .form-options {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            font-size: 12px;
        }
        .remember-me {
            display: flex;
            align-items: center;
            gap: 6px;
            color: var(--gray-600);
            cursor: pointer;
        }
        .remember-me input { 
            width: 14px; 
            height: 14px; 
            accent-color: var(--accent); 
            cursor: pointer;
        }
        .forgot-link {
            color: var(--accent);
            text-decoration: none;
            font-weight: 500;
        }
        .forgot-link:hover { text-decoration: underline; }
        
        /* Submit Button */
        .btn-login {
            width: 100%;
            padding: 14px;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: var(--radius);
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: var(--transition);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        .btn-login:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }
        .btn-login:active { transform: translateY(0); }
        .btn-login:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            transform: none !important;
        }
        .btn-login .spinner {
            display: none;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255,255,255,0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
        .btn-login.loading .btn-text { display: none; }
        .btn-login.loading .spinner { display: inline-block; }
        @keyframes spin { to { transform: rotate(360deg); } }
        
        /* Footer Links */
        .login-footer {
            text-align: center;
            padding: 16px 24px 24px;
            font-size: 12px;
            color: var(--gray-500);
        }
        .login-footer a {
            color: var(--accent);
            text-decoration: none;
            font-weight: 500;
        }
        .login-footer a:hover { text-decoration: underline; }
        
        /* Security Badge */
        .security-badge {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            margin-top: 16px;
            padding: 8px 12px;
            background: var(--gray-100);
            border-radius: 20px;
            font-size: 10px;
            color: var(--gray-600);
            font-weight: 500;
        }
        .security-badge i { color: var(--success); }
        
        /* Responsive */
        @media (max-width: 480px) {
            .login-wrapper { max-width: 100%; }
            .login-card { border-radius: var(--radius); }
        }
        
        /* Print Hide */
        @media print { body { display: none; } }
    </style>
</head>
<body>

<div class="login-wrapper">
    <!-- Brand Header -->
    <div class="login-brand">
        <div class="brand-logo">
        <img src="assets/img/clm_logo3.png" alt="LOGO CLM" width="55" height="55">
        </div>
        <div class="brand-name">PT CITRA LAMPIA MANDIRI</div>
        <div class="brand-subtitle">Safety Talk System • QHSEF Department</div>
    </div>

    <!-- Login Card -->
    <div class="login-card">
        <div class="login-header">
            <h2><i class="fas fa-user-lock"></i> Login Pengguna</h2>
            <p>Masukkan kredensial untuk mengakses sistem</p>
        </div>
        
        <div class="login-body">
            <!-- Alert Messages -->
            <?php if($error): ?>
            <div class="alert alert-error" role="alert">
                <i class="fas fa-circle-exclamation"></i>
                <span><?= htmlspecialchars($error) ?></span>
            </div>
            <?php endif; ?>
            <?php if($success): ?>
            <div class="alert alert-success" role="alert">
                <i class="fas fa-circle-check"></i>
                <span><?= htmlspecialchars($success) ?></span>
            </div>
            <?php endif; ?>
            
            <!-- Login Form -->
            <form method="POST" id="loginForm" autocomplete="off">
                <div class="form-group">
                    <label for="nama"><i class="fas fa-user"></i> Nama Pengguna</label>
                    <input type="text" id="nama" name="nama" class="form-control" 
                           placeholder="Contoh: admin" 
                           value="<?= $oldNama ?>" 
                           required autofocus>
                </div>
                
                <div class="form-group">
                    <label for="password"><i class="fas fa-lock"></i> Password</label>
                    <div class="password-wrapper">
                        <input type="password" id="password" name="password" class="form-control" 
                               placeholder="••••••••" required>
                        <button type="button" class="password-toggle" onclick="togglePassword()" 
                                aria-label="Tampilkan password">
                            <i class="fas fa-eye" id="toggleIcon"></i>
                        </button>
                    </div>
                </div>
                
                <div class="form-options">
                    <label class="remember-me">
                        <input type="checkbox" name="remember" value="1">
                        <span>Ingat saya</span>
                    </label>
                    <a href="mailto:aulizar@citralampiamandiri.biz" class="forgot-link">Lupa password?</a>
                </div>
                
                <button type="submit" class="btn-login" id="btnSubmit">
                    <span class="btn-text"><i class="fas fa-sign-in-alt"></i> Masuk Sistem</span>
                    <span class="spinner"></span>
                </button>
            </form>
            
            <!-- Security Badge -->
            <div class="security-badge">
                <i class="fas fa-lock"></i>
                <span>Koneksi aman • Session Asia/Jakarta</span>
            </div>
        </div>
        
        <div class="login-footer">
            <p>Belum punya akses? Hubungi <a href="mailto:aulizar@citralampiamandiri.biz">Admin QHSEF</a></p>
            <p style="margin-top:8px; font-size:10px; opacity:0.7">
                <i class="fas fa-info-circle"></i> Sistem v<?= defined('APP_VERSION') ? APP_VERSION : '2.4.2' ?>
            </p>
        </div>
    </div>
</div>

<script>
// Toggle Password Visibility
function togglePassword() {
    const input = document.getElementById('password');
    const icon = document.getElementById('toggleIcon');
    
    if(input.type === 'password') {
        input.type = 'text';
        icon.className = 'fas fa-eye-slash';
    } else {
        input.type = 'password';
        icon.className = 'fas fa-eye';
    }
    input.focus();
}

// Form Submit with Loading State
document.getElementById('loginForm').addEventListener('submit', function(e) {
    const btn = document.getElementById('btnSubmit');
    
    // Only add loading if no error/success message shown
    if(!document.querySelector('.alert-success')) {
        btn.classList.add('loading');
        btn.disabled = true;
    }
});

// Enter key on password field submits form
document.getElementById('password').addEventListener('keypress', function(e) {
    if(e.key === 'Enter') {
        e.preventDefault();
        document.getElementById('loginForm').requestSubmit();
    }
});

// Auto-focus nama field on load
document.addEventListener('DOMContentLoaded', function() {
    const namaInput = document.getElementById('nama');
    if(namaInput && !namaInput.value) {
        namaInput.focus();
    }
    
    // Clear success message after redirect delay
    const successAlert = document.querySelector('.alert-success');
    if(successAlert) {
        setTimeout(() => {
            successAlert.style.opacity = '0';
            successAlert.style.transform = 'translateY(-10px)';
        }, 1000);
    }
});

// Keyboard shortcut: Ctrl+Enter to submit
document.addEventListener('keydown', function(e) {
    if((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
        e.preventDefault();
        document.getElementById('loginForm').requestSubmit();
    }
});
</script>

</body>
</html>