<?php
session_start();
require_once 'web_constant.php';
date_default_timezone_set("Asia/Kolkata");
include('DB.php');
$bdd = new DB();

if (isset($_POST['login'])) {

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

    // ❌ Plain password check (keep for now)
    $values = array($username, $password);

    $row = $bdd->getOne(
        "SELECT id, username, password, user_type 
         FROM users 
         WHERE username=? AND password=?",
        $values
    );

    if ($row) {

        // 🔐 BASIC USER SESSION
        $_SESSION['user_id']   = $row['id'];
        $_SESSION['username']  = $row['username'];
        $_SESSION['user_type'] = $row['user_type'];

        // 🔑 LOAD USER PERMISSIONS (ONCE)
        $permRows = $bdd->getAll(
            "SELECT page_key, can_view, can_edit, can_delete, other_permissions 
             FROM user_permissions 
             WHERE user_id = ?",
            array($row['id'])
        );

        $permissions = [];

        foreach ($permRows as $perm) {
            // Parse other_permissions from JSON string
            $otherPerms = [];
            if (!empty($perm['other_permissions'])) {
                $otherPerms = json_decode($perm['other_permissions'], true);
                if (!is_array($otherPerms)) {
                    $otherPerms = [];
                }
            }

            $permissions[$perm['page_key']] = [
                'view'   => (bool)$perm['can_view'],
                'edit'   => (bool)$perm['can_edit'],
                'delete' => (bool)$perm['can_delete'],
                'other'  => $otherPerms
            ];
        }

        $_SESSION['permissions'] = $permissions;

        // ✅ REDIRECT
        header("Location: home");
        exit;

    } else {
        echo "<script>alert('Wrong username or password');</script>";
    }
}

$bdd->disconnect();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="shortcut icon" type="image/png" href="favicon.png" />
  <title><?php echo web_constant::APP_NAME;?></title>

  <!-- Google Font: Source Sans Pro -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
  <!-- icheck bootstrap -->
  <!-- Theme style -->
  <link rel="stylesheet" href="dist/css/adminlte.min.css">
</head>
<body class="hold-transition login-page">
<div class="login-box">
  <!-- /.login-logo -->
  <div class="card card-outline card-primary">
    <div class="card-header text-center">
      <a href="#" class="h1"><b><?php echo web_constant::APP_NAME;?></b></a>
    </div>
    <div class="card-body">
      <p class="login-box-msg">Sign in to start your session</p>

      <form method="post">
        <div class="input-group mb-3">
          <input type="text" name="username" class="form-control" placeholder="Username" autofocus="autofocus">
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-envelope"></span>
            </div>
          </div>
        </div>
        <div class="input-group mb-3">
          <input type="password" name="password" class="form-control" placeholder="Password">
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-lock"></span>
            </div>
          </div>
        </div>
        <div class="row">
          
          <!-- /.col -->
		  <div class="col-4"></div>
          <div class="col-4">
            <button type="submit" name="login" class="btn btn-primary btn-block">Sign In</button>
          </div>
		  <div class="col-4"></div>
          <!-- /.col -->
        </div>
      </form>

      
    </div>
    <!-- /.card-body -->
  </div>
  <!-- /.card -->
</div>
<!-- /.login-box -->

<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
</body>
</html>