<?php
// Start session
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Check if user is already logged in
if (isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// Handle login form submission
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    require_once __DIR__ . '/config/config.php';

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

    if (empty($username) || empty($password)) {
        $error = 'Please enter both username and password.';
    } else {
        try {
            // Authenticate against tbl_user
            $stmt = $pdo->prepare("SELECT * FROM `tbl_user` WHERE username = :username");
            $stmt->bindParam(':username', $username, PDO::PARAM_STR);
            $stmt->execute();
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user) {
                // Check password (plain text comparison as per existing API)
                if ($password == $user['password']) {
                    // Set session variables
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['user_id'] = $user['user_id'];
                    $_SESSION['role_id'] = $user['role_id'];
                    $_SESSION['user_type'] = $user['user_type'] ?? 'both';

                    // Fetch extended user details (Employee Name, Designation)
                    if (function_exists('fetch_user_extended_details')) {
                        $details = fetch_user_extended_details($user['user_id'], $user['username'], $user['role_id'], $_SESSION['user_type']);
                    } else {
                        $details = ['name' => $user['username'], 'designation' => 'User'];
                    }

                    $_SESSION['employee_name'] = $details['name'];
                    $_SESSION['designation'] = $details['designation'];

                    // Store device/browser information
                    $_SESSION['device_info'] = [
                        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                        'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
                        'login_time' => date('Y-m-d H:i:s'),
                        'session_id' => session_id()
                    ];

                    // Redirect to dashboard
                    header("Location: index.php");
                    exit();
                } else {
                    $error = 'Invalid password.';
                }
            } else {
                $error = 'User credentials not found.';
            }
        } catch (PDOException $e) {
            $error = 'Database error: ' . $e->getMessage();
        }
    }
}
?>
<!doctype html>
<html lang="en" dir="ltr">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Srihari Agencies - Login</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="shortcut icon" href="assets/Ganesan/srihari.png">

    <meta name="keywords" content="Srihari Agencies, eCommerce Shipping in India">
    <meta name="title" content="Srihari Agencies, Shipping and Courier Services in India." />
    <meta name="description"
        content="Srihari Agencies is leading logistics, shipping and courier solution provider in India. An E-commerce logistics and courier aggregator that lets you ship at discounted rates. Automated shipping solutions for making shipping fast, secure and easy. Get Started Today." />

    <meta property="og:url" content="" />
    <meta property="og:image" content="assets/Ganesan/srihari.png" />
    <meta property="og:title" content="Srihari Agencies, Shipping and Courier Services in India." />
    <meta property="og:description"
        content="Srihari Agencies is leading logistics, shipping and courier solution provider in India. Contact us for Cargo and Courier Services." />

    <link href="assets/Ganesan/flatpickr/dist/flatpickr.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/Ganesan/qompac-ui.minf700.css?v=1.0.1" rel="stylesheet" type="text/css" />
    <link href="assets/Ganesan/custom.minf700.css?v=1.0.1" rel="stylesheet" type="text/css" />
    <link href="assets/Ganesan/customizer.minf700.css?v=1.0.1" rel="stylesheet" type="text/css" />

    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link
        href="https://fonts.googleapis.com/css2?family=Heebo:wght@100;200;300;400;500;600;700;800;900&amp;display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
        integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />

    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="assets/Ganesan/jquery-3.3.1.min.js"></script>

    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-45KP6Z41QY"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag() { dataLayer.push(arguments); }
        gtag('js', new Date());
        gtag('config', 'G-45KP6Z41QY');
    </script>
    <script language="javascript">
        function checkInput(ob) {
            var invalidChars = /[^0-9.]/gi;
            if (invalidChars.test(ob.value)) {
                ob.value = ob.value.replace(invalidChars, "");
            }
        }
        function removeSpace(ob) {
            var invalidChars = /\s/g;
            if (invalidChars.test(ob.value)) {
                ob.value = ob.value.replace(invalidChars, "");
            }
        }
        function checkNumber(ob) {
            var invalidChars = /[^0-9.,]/gi;
            if (invalidChars.test(ob.value)) {
                ob.value = ob.value.replace(invalidChars, "");
            }
        }
        var csrfName = 'csrf_trux', csrfHash = 'cf959232b9ae36e57d8ffabdd529f5e8';
        document.addEventListener("contextmenu", function (e) {
            e.preventDefault();
        }, false);
        document.onkeydown = function (e) {
            if (e.ctrlKey && e.keyCode === 85) { return false; }
            if (e.shiftKey && (e.which == 188 || e.which == 190)) {
                e.preventDefault();
            }
        };
        $(function () {
            $('input').on("keydown", function (e) {
                if (e.shiftKey && (e.which == 188 || e.which == 190)) {
                    e.preventDefault();
                }
            });
        });
        $(document).on('input', 'input, textarea', function (e) {
            if (e.originalEvent.inputType == 'insertFromPaste') {
                var regex = new RegExp("^[a-zA-Z0-9@. ]+$");
                if (regex.test($(this).val())) { }
                else { alert('Only english language characters accepted.'); $(this).val($(this).val().replace(/[^A-Za-z0-9@. ]/g, '').trim()); }
            }
        });
    </script>
    <script>
        $(document).ready(function () {
            var invalidChars = /[&\%#;]/;
            $('input').keyup(function () {
                if (invalidChars.test($(this).val())) {
                    var str = $(this).val();
                    var res = str.replace(invalidChars, "");
                    $(this).val(res);
                    alert("These 5 special characters(& '/' % # ;) are not allowed. ");
                }
            });
        });
    </script>
    <style>
        .pull-left {
            float: left
        }

        #ui-datepicker-div {
            z-index: 9999 !important;
        }
    </style>
</head>

<body class="container-width"
    style="background-image: url('assets/Ganesan/auth.jpg'); background-size: cover; background-position: center;">
    <!-- loader Start -->
    <div id="loading">
        <div class="loader1 simple-loader">
            <div class="loader-body ">
                <img src="assets/Ganesan/loader.gif" class="logo-title" style="width:5% " alt="loader"
                    class="image-loader img-fluid ">
            </div>
        </div>
    </div>
    <!-- loader END -->
    <style>
        .form-control {
            border: 0;
            padding: 10px 30px 10px 39px;
            box-shadow: 0px 1px 5px 0px white;
            border-radius: 8px;
            height: 40px;
            font-size: 14px;
        }

        .form-group i {
            position: absolute;
            padding: 10px 12px 10px 13px;
            color: white;
            border-radius: 8px 0px 0px 8px;
            height: 39px;
            margin-bottom: 3px;
        }

        .purle {
            color: white
        }

        input:focus {
            box-shadow: 0px 1px 5px 0px white !important;
        }

        .gimg {
            width: 23px;
            margin-right: 10px;
            vertical-align: middle;
        }
    </style>
    <section class="login-section"
        style="background-image: url('assets/Ganesan/auth.jpg'); background-size: cover; background-position: center;">
        <div class="klogin">
            <div class="row" style="z-index: 1">
                <div class="col-lg-6 di-none">
                    <img class="w-100">
                </div>
                <div class="col-lg-6">
                    <div class="login_form" style="margin-top: 10%;padding: 20px;background-color: #99969654;">
                        <div class="brand-logo text-center">
                            <a href="">
                                <img class="logo-title w-50 mb-4" src="assets/Ganesan/srihari.png" alt=""
                                    style="width: 130px !important;">
                            </a>
                        </div>
                        <h2 class="main-heading">Sign In</h2>
                        <div class="form-group">
                            <h6 style="color:white !important;font-weight: bold;">Hello! let's get started</h6>
                        </div>
                        <div class="userContent">
                            <?php if (!empty($error)): ?>
                                <div class="alert alert-danger alert-dismissible fade show" role="alert"
                                    style="background-color: #f8d7da; color: #721c24; border-color: #f5c6cb; padding: 10px; border-radius: 5px; margin-bottom: 15px;">
                                    <i class="fa fa-exclamation-circle me-2"></i>
                                    <?php echo htmlspecialchars($error); ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"
                                        style="float: right; background: none; border: none; font-size: 20px; cursor: pointer;">&times;</button>
                                </div>
                            <?php endif; ?>
                        </div>
                        <form action="" autocomplete="off" method="post" accept-charset="utf-8">
                            <div class="row">
                                <div class="col-lg-12">
                                    <div class="form-group mb-4">
                                        <i class="fa fa-user"></i>
                                        <input type="text" name="username"
                                            value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
                                            class="form-control login-input" placeholder="Username" required>
                                    </div>
                                </div>
                                <div class="col-lg-12">
                                    <div class="form-group mb-1">
                                        <i class="fa fa-lock"></i>
                                        <div style="display:flex">
                                            <input type="password" id="password" name="password" value=""
                                                class="form-control login-input" placeholder="Password" required>
                                            <span toggle="#password-field"
                                                class="fa fa-fw fa-eye field_icon toggle-password"
                                                style="margin-top: 11px; margin-left: -27px; cursor: pointer; z-index: 10;"></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-12 mt-4 d-flex justify-content-between align-items-center">
                                    <div class="form-check">
                                        <label class="form-check-label">
                                            <input type="checkbox" name="remember" class="form-check-input"> &nbsp;
                                            <small style="color:white !important;font-weight: bold;"> Keep me signed
                                                in</small>
                                        </label>
                                    </div>
                                    <a href="" class="auth-link text-black"
                                        style="font-size: 14px;color:white !important;font-weight: bold;">Forgot
                                        Password?</a>
                                </div>

                                <div class="col-lg-12 mt-1 mb-3 mt-4">
                                    <button type="submit" class="btn btn-primary btn-login lh-lg w-100">Login
                                        Now</button>
                                    <h6 class="text-center mt-2">or</h6>
                                </div>

                            </div>
                        </form>
                        <div class="mb-2">
                            <div class="row">
                                <div class="text-center col-lg-6">
                                    <button style="color:white !important;font-weight: bold;"
                                        class="btn btn-outline-primary w-100"><i class="ti-facebook"></i> Login With
                                        OTP</button>
                                </div>
                                <div class="text-center col-lg-6">
                                    <button type="button" style="color:white !important;font-weight: bold;"
                                        class="btn btn-outline-light btn-google w-100">
                                        <img class="gimg" src="">Sign in Google
                                    </button>
                                </div>

                            </div>
                        </div>
                        <hr>
                        <div class="text-center row">
                            <div class="col-lg-12" style="color:white !important;font-weight: bold;"> Don't have an
                                account? <a style="color:white; cursor: pointer;"><b>Register Now</b></a></div>
                        </div>
                    </div>

                </div>
            </div>
        </div>

    </section>
    <script>
        $("body").on('click', '.toggle-password', function () {
            $(this).toggleClass("fa-eye fa-eye-slash");
            var input = $("#password").attr("type");
            if (input === "password") { $("#password").attr("type", "text"); }
            else { $("#password").attr("type", "password"); }
        });
    </script>
    <script src="https://b2b.truxcargo.com/assets/js/qompac-uif700.js?v=1.0.1" defer></script>

</body>

</html>