<?php
include_once("model/db.php");

/* دالة إرجاع IP */
function getUserIp()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ipList[0]);
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username'], $_POST['password'])) {

    $username = trim($_POST['username']);
    $pass     = trim($_POST['password']);

    if ($username === "" || $pass === "") {
        $error = "⚠️ من فضلك أدخل اسم المستخدم وكلمة المرور";
    } else {

        // ✅ استخدام Prepared Statement للحماية من SQL Injection
        $stmt = mysqli_prepare($db, "SELECT * FROM `emp` WHERE `username` = ? AND `password` = ? LIMIT 1");
        mysqli_stmt_bind_param($stmt, "ss", $username, $pass);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        if ($result && mysqli_num_rows($result) === 1) {

            $row       = mysqli_fetch_assoc($result);
            $idEmp     = $row['id_emp'];
            $idUser    = $row['id_user'];
            $typeLogin = $row['active_emp']; // 0 = شغال, 1 = محذوف

            // تسجيل الدخول في log_login
            $ip   = getUserIp();
            $stmtLog = mysqli_prepare(
                $db,
                "INSERT INTO `log_login` (`id_emp`,`id_user`,`type_login`,`ip_address`) VALUES (?,?,?,?)"
            );
            mysqli_stmt_bind_param($stmtLog, "iiis", $idEmp, $idUser, $typeLogin, $ip);
            mysqli_stmt_execute($stmtLog);

            if ($row['active_emp'] == 1) {
                $error = "🚫 تم حذف هذا الحساب ولا يمكنه تسجيل الدخول";
            } else {

                // تخزين بيانات الجلسة
                $_SESSION['id_user']    = $row['id_emp'];
                $_SESSION['id_account'] = $row['id_user'];
                $_SESSION['name_emp']   = $row['name_emp'];
                $_SESSION['powersEmp']  = [];

                // جلب الصلاحيات
                $stmtPow = mysqli_prepare(
                    $db,
                    "SELECT `type_power` FROM `powers` WHERE `id_emp` = ? ORDER BY `power` ASC"
                );
                mysqli_stmt_bind_param($stmtPow, "i", $idEmp);
                mysqli_stmt_execute($stmtPow);
                $resPow = mysqli_stmt_get_result($stmtPow);

                while ($rowPowers = mysqli_fetch_assoc($resPow)) {
                    $_SESSION['powersEmp'][] = $rowPowers['type_power'];
                }

                echo "<script>window.location.href = 'index.php';</script>";
                exit;
            }

        } else {
            $error = "⚠️ اسم المستخدم أو كلمة المرور غير صحيحة";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>تسجيل الدخول - PROG EGYPT</title>

    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link
        href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;700&display=swap"
        rel="stylesheet">

    <link href="css/sb-admin-2.min.css" rel="stylesheet">

    <style>
        body {
            font-family: 'Cairo', sans-serif;
            background: #f5f7fb;
        }

        .login-wrapper {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-card {
            max-width: 420px;
            width: 100%;
            border-radius: 20px;
            border: none;
            box-shadow: 0 10px 30px rgba(15, 23, 42, 0.15);
        }

        .login-card .card-body {
            padding: 2.5rem 2.25rem;
        }

        .login-title {
            font-weight: 700;
            color: #1565C0;
        }

        .login-subtitle {
            font-size: 0.9rem;
            color: #90A4AE;
        }

        .form-control-user {
            border-radius: 12px;
        }

        .btn-login {
            border-radius: 12px;
            font-weight: 600;
            padding: 0.6rem 1rem;
        }

        .error {
            color: #e53935;
            margin-bottom: 10px;
            font-size: 0.9rem;
        }

        .login-logo {
            width: 150px;
            height: 150px;
            object-fit: contain;
            margin-bottom: 0.75rem;
        }

        .login-footer {
            margin-top: 1.5rem;
            font-size: 0.8rem;
            color: #b0bec5;
            text-align: center;
        }
    </style>

</head>

<body>

    <div class="container login-wrapper">

        <div class="card login-card">
            <div class="card-body">

                <div class="text-center mb-4">
                    <!-- غيّر مسار اللوجو حسب مكان الصورة عندك -->
                    <img src="img/pe.png" alt="PROG EGYPT" class="login-logo">
                    <h1 class="h4 login-title mb-1">مرحبا بعودتك 👋</h1>
                    <div class="login-subtitle">من فضلك قم بتسجيل الدخول للمتابعة إلى النظام</div>
                </div>

                <form class="user" method="POST" autocomplete="off">

                    <?php if (!empty($error)): ?>
                        <div class="error text-center"><?= $error ?></div>
                    <?php endif; ?>

                    <div class="form-group mb-3">
                        <label class="small mb-1">اسم المستخدم</label>
                        <input name="username" type="text"
                               class="form-control form-control-user"
                               placeholder="ادخل اسم المستخدم"
                               required>
                    </div>

                    <div class="form-group mb-3">
                        <label class="small mb-1">كلمة المرور</label>
                        <input name="password" type="password"
                               class="form-control form-control-user"
                               placeholder="ادخل كلمة المرور"
                               required>
                    </div>

                    <div class="form-group d-flex justify-content-between align-items-center mb-4">
                        <div class="custom-control custom-checkbox small">
                            <input type="checkbox" class="custom-control-input" id="customCheck">
                            <label class="custom-control-label" for="customCheck">تذكرني</label>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary btn-user btn-login btn-block">
                        دخول
                    </button>

                    <div class="login-footer">
                        Powered by PROG EGYPT
                    </div>

                </form>

            </div>
        </div>

    </div>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>

</body>

</html>
