<?php
// =============================================
// SHARK CRM - Login Page
// =============================================
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

require_once 'connect.php';

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email    = sanitize($conn, $_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($email && $password) {
        // Get full user data with role information
        $stmt = $conn->prepare("
            SELECT u.*, r.name as role_name, r.permissions 
            FROM users u 
            LEFT JOIN roles r ON u.role_id = r.id 
            WHERE u.email = ?
        ");
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();

        if ($user && password_verify($password, $user['password'])) {
            // Store all relevant user data in session
            $_SESSION['user_id']     = $user['id'];
            $_SESSION['user_name']   = $user['name'];
            $_SESSION['user_email']  = $user['email'];
            $_SESSION['account_id']  = $user['account_id'];
            $_SESSION['user_role']   = $user['role_name'] ?? 'User';
            $_SESSION['role_id']     = $user['role_id'];
            $_SESSION['permissions'] = json_decode($user['permissions'] ?? '[]', true);
            
            // Optional: Log login activity
            $login_time = date('Y-m-d H:i:s');
            $user_id = $user['id'];
            $conn->query("UPDATE users SET last_login = '$login_time' WHERE id = $user_id");
            
            header('Location: index.php');
            exit;
        } else {
            $error = 'Invalid email or password.';
        }
    } else {
        $error = 'Please fill in all fields.';
    }
}

// Function to check if user is logged in (useful for API calls)
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Function to get current user ID
function getCurrentUserId() {
    return $_SESSION['user_id'] ?? 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shark CRM – Login</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="login-page">
  <div class="login-card fade-in">
    <div class="login-logo">
      <div class="login-logo-icon">🦈</div>
      <h1>SHARK <span>CRM</span></h1>
      <p>SALES INTELLIGENCE PLATFORM</p>
    </div>

    <?php if ($error): ?>
      <div class="login-error">⚠ <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST">
      <div class="form-group">
        <label class="form-label">Email Address</label>
        <input type="email" name="email" class="form-control" placeholder="admin@sharkcrm.com"
               value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required autofocus>
      </div>

      <div class="form-group">
        <label class="form-label">Password</label>
        <input type="password" name="password" class="form-control" placeholder="••••••••" required>
      </div>

      <button type="submit" class="btn btn-primary w-full btn-lg" style="margin-top:8px">
        Sign In →
      </button>
    </form>

    <div style="text-align:center;margin-top:20px;font-size:12px;color:var(--text-muted)">
      Demo: admin@sharkcrm.com / admin123
    </div>
  </div>
</div>
<div id="toast-container"></div>
<script src="assets/js/main.js"></script>
</body>
</html>