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


    <?php if (!empty($_GET['reset_token']) && !empty($_GET['email'])): ?>
      <form onsubmit="return resetPassword(event)">
        <input type="hidden" id="resetEmail" value="<?= htmlspecialchars($_GET['email']) ?>">
        <input type="hidden" id="resetToken" value="<?= htmlspecialchars($_GET['reset_token']) ?>">
        <div class="form-group">
          <label class="form-label">New Password</label>
          <input type="password" id="newResetPassword" class="form-control" required minlength="6">
        </div>
        <button type="submit" class="btn btn-primary w-full btn-lg" style="margin-top:8px">Update Password</button>
      </form>
    <?php else: ?>
    <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:14px">
        <a href="#" onclick="showForgotBox();return false;" style="font-size:13px;color:var(--accent)">Forgot password?</a>
      </div>
      <div id="forgotBox" style="display:none;margin-top:14px;padding:12px;border:1px solid var(--border);border-radius:12px;background:var(--bg-base)">
        <label class="form-label">Your email</label>
        <input type="email" id="forgotEmail" class="form-control" placeholder="email@example.com">
        <button class="btn btn-secondary w-full" style="margin-top:8px" onclick="requestReset()">Send reset link</button>
      </div>
    <?php endif; ?>

    <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>
<script>
function showForgotBox(){ document.getElementById('forgotBox').style.display='block'; }
async function requestReset(){
  const email = document.getElementById('forgotEmail').value.trim();
  if(!email){ alert('Enter your email'); return; }
  const fd = new FormData(); fd.append('action','request'); fd.append('email', email);
  const r = await fetch('handlers/forgot_password.php',{method:'POST',body:fd});
  const j = await r.json(); alert(j.message || 'Check your email');
}
async function resetPassword(e){
  e.preventDefault();
  const fd = new FormData();
  fd.append('action','reset');
  fd.append('email', document.getElementById('resetEmail').value);
  fd.append('token', document.getElementById('resetToken').value);
  fd.append('password', document.getElementById('newResetPassword').value);
  const r = await fetch('handlers/forgot_password.php',{method:'POST',body:fd});
  const j = await r.json(); alert(j.message || 'Done');
  if(j.success) location.href='index.php?page=login';
  return false;
}
</script>
</body>
</html>