<?php
session_start();
require_once "config/database.php";

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$message = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $login = trim($_POST['login'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if ($login === "" || $password === "") {
        $message = "Please fill all fields";
    } else {
        $query = "SELECT * FROM users
                  WHERE (username = :login OR email = :login)
                  AND status = 'active'
                  LIMIT 1";

        $stmt = $db->prepare($query);
        $stmt->bindParam(":login", $login);
        $stmt->execute();

        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['full_name'] = $user['full_name'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];

            $_SESSION['workspace_type'] = 'personal';
            $_SESSION['active_company_id'] = null;
            $_SESSION['company_name'] = '';
            $_SESSION['company_ids'] = [];
            $_SESSION['companies'] = [];

            $stmtCompanies = $db->prepare("
                SELECT c.id, c.company_name
                FROM company_users cu
                INNER JOIN companies c ON c.id = cu.company_id
                WHERE cu.user_id = :user_id
                ORDER BY c.company_name ASC
            ");
            $stmtCompanies->bindValue(':user_id', (int)$user['id'], PDO::PARAM_INT);
            $stmtCompanies->execute();

            $userCompanies = $stmtCompanies->fetchAll(PDO::FETCH_ASSOC);

            if (!empty($userCompanies)) {
                $_SESSION['companies'] = $userCompanies;
                $_SESSION['company_ids'] = array_map('intval', array_column($userCompanies, 'id'));
                $_SESSION['active_company_id'] = (int)$userCompanies[0]['id'];
                $_SESSION['company_name'] = $userCompanies[0]['company_name'] ?? '';
            }

                    header("Location: my_documents.php?workspace=personal&scope=personal");
            exit;
                    } else {
                        $message = "Invalid login";
                    }
                }
            }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - DocuTrack</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <style>
        body {
            margin: 0;
            background: linear-gradient(135deg, #f4f7fb 0%, #e9eef6 100%);
            font-family: Arial, sans-serif;
        }

        .auth-page {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24px;
        }

        .auth-wrap {
            width: 100%;
            max-width: 980px;
            display: grid;
            grid-template-columns: 1fr 420px;
            background: #fff;
            border-radius: 24px;
            overflow: hidden;
            box-shadow: 0 20px 50px rgba(16, 24, 40, 0.12);
        }

        .auth-left {
            background: linear-gradient(135deg, #1d4ed8, #2563eb);
            color: #fff;
            padding: 48px;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .auth-left .logo {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            font-size: 32px;
            font-weight: 800;
            margin-bottom: 24px;
        }

        .logo-box {
            background: #ffffff;
            padding: 10px 14px;
            border-radius: 10px;
            margin-bottom: 12px;
            display: inline-block;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }

        .logo-box img {
            width: 60px;
            height: auto;
            display: block;
        }

        .auth-left .logo span {
            color: #bfdbfe;
        }

        .auth-left h1 {
            font-size: 36px;
            margin: 0 0 16px;
            line-height: 1.2;
        }

        .auth-left p {
            margin: 0;
            font-size: 16px;
            line-height: 1.7;
            color: rgba(255,255,255,0.9);
        }

        .auth-right {
            padding: 40px 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #ffffff;
        }

        .login-card {
            width: 100%;
        }

        .login-card .section-title {
            font-size: 28px;
            margin-bottom: 8px;
        }

        .login-card .section-subtext {
            margin-bottom: 24px;
            color: #667085;
        }

        .form-group {
            margin-bottom: 18px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 8px;
            color: #344054;
        }

        .form-group input {
            width: 100%;
            box-sizing: border-box;
            padding: 12px 14px;
            border: 1px solid #d0d5dd;
            border-radius: 12px;
            font-size: 15px;
            background: #fff;
        }

        .form-group input:focus {
            outline: none;
            border-color: #2563eb;
            box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.12);
        }

        .alert-box {
            margin-bottom: 18px;
            padding: 12px 14px;
            border-radius: 12px;
            font-size: 14px;
        }

        .alert-danger {
            background: #fef3f2;
            color: #b42318;
            border: 1px solid #fecdca;
        }

        .auth-actions {
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-top: 8px;
        }

        .auth-actions .btn {
            width: 100%;
            text-align: center;
            text-decoration: none;
            box-sizing: border-box;
        }

        .auth-links {
            margin-top: 20px;
            text-align: center;
            font-size: 14px;
            color: #667085;
        }

        .auth-links a,
        .forgot-link {
            color: #2563eb;
            text-decoration: none;
            font-weight: 600;
        }

        .forgot-wrap {
            margin-top: -6px;
            margin-bottom: 18px;
            text-align: right;
            font-size: 14px;
        }

        .guest-link {
            display: inline-block;
            margin-top: 10px;
        }

        @media (max-width: 900px) {
            .auth-wrap {
                grid-template-columns: 1fr;
            }

            .auth-left {
                padding: 32px 24px;
            }

            .auth-right {
                padding: 32px 24px;
            }
        }
    </style>
</head>
<body>
    <div class="auth-page">
        <div class="auth-wrap">
            <div class="auth-left">
                <div class="logo">
                    <div class="logo-box">
                        <img src="assets/images/logo.png" alt="Logo">
                    </div>
                    <div>Docu<span>Track</span></div>
                </div>

                <h1>Welcome back</h1>
                <p>
                    Manage your documents, contracts, reminders, and vehicle records
                    in one place with a clean and simple dashboard.
                </p>
            </div>

            <div class="auth-right">
                <div class="login-card">
                    <div class="section-title">Login</div>
                    <div class="section-subtext">Sign in to access your account.</div>

                    <?php if ($message !== ""): ?>
                        <div class="alert-box alert-danger">
                            <?php echo htmlspecialchars($message); ?>
                        </div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="form-group">
                            <label for="login">Username or Email</label>
                            <input
                                type="text"
                                name="login"
                                id="login"
                                value="<?php echo htmlspecialchars($_POST['login'] ?? ''); ?>"
                                placeholder="Enter username or email"
                                required
                            >
                        </div>

                        <div class="form-group">
                            <label for="password">Password</label>
                            <input
                                type="password"
                                name="password"
                                id="password"
                                placeholder="Enter password"
                                required
                            >
                        </div>

                        <div class="forgot-wrap">
                            <a href="forgot_password.php" class="forgot-link">Forgot password?</a>
                        </div>

                        <div class="auth-actions">
                            <button type="submit" class="btn btn-primary">Login</button>
                            <a href="guest_login.php" class="btn btn-secondary">Continue as Guest</a>
                        </div>
                    </form>

                    <div class="auth-links">
                        Don’t have an account?
                        <a href="register.php">Register</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>