<?php
session_start();
require_once 'db.php';

// Konfigurasi Google OAuth (Dinamis menyesuaikan domain lokal / online hosting)
$google_client_id = '808762497378-hof7dlvqqpl7je56sh6joufao404u52p.apps.googleusercontent.com'; 
$scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$dir = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$google_redirect_uri = "$scheme://$host$dir/google_callback.php";

// Redirect jika sudah login
if(isset($_SESSION['user_id'])) {
    if($_SESSION['role'] === 'superadmin') {
        header("Location: superadmin.php");
    } elseif ($_SESSION['role'] === 'pimpinan') {
        header("Location: dashboard_executive.php");
    } else {
        header("Location: index.php");
    }
    exit;
}

$error = '';

// Menangkap pesan error dari sesi (misal dari Google Callback)
if (isset($_SESSION['login_error'])) {
    $error = $_SESSION['login_error'];
    unset($_SESSION['login_error']);
}

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

    if(!empty($username) && !empty($password)) {
        // Prepared statement anti SQL Injection
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? LIMIT 1");
        $stmt->execute([$username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if($user && password_verify($password, $user['password'])) {
            // Cek status instansi untuk admin instansi
            $can_login = true;
            if ($user['role'] !== 'superadmin' && !empty($user['instansi_id'])) {
                $stmt_instansi = $pdo->prepare("SELECT status FROM instansi WHERE id = ?");
                $stmt_instansi->execute([$user['instansi_id']]);
                $instansi = $stmt_instansi->fetch(PDO::FETCH_ASSOC);
                
                if ($instansi && $instansi['status'] !== 'aktif') {
                    $can_login = false;
                    $error = "Akses ditolak: Akun Instansi sedang ditangguhkan (Suspend). Silakan hubungi Superadmin.";
                }
            }

            if ($can_login) {
                // Set session
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['instansi_id'] = $user['instansi_id'];

                if($user['role'] === 'superadmin') {
                    header("Location: superadmin.php");
                } elseif ($user['role'] === 'pimpinan') {
                    header("Location: dashboard_executive.php");
                } else {
                    header("Location: index.php");
                }
                exit;
            }
        } else {
            $error = "Username atau Password salah!";
        }
    } else {
        $error = "Mohon isi username dan password.";
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Login | MonitorDaerah</title>
  <!-- plugins:css -->
  <link rel="stylesheet" href="assets_skydash/vendors/feather/feather.css">
  <link rel="stylesheet" href="assets_skydash/vendors/ti-icons/css/themify-icons.css">
  <link rel="stylesheet" href="assets_skydash/vendors/css/vendor.bundle.base.css">
  <link rel="stylesheet" href="assets_skydash/vendors/font-awesome/css/font-awesome.min.css">
  <!-- inject:css -->
  <link rel="stylesheet" href="assets_skydash/css/style.css">
  <!-- endinject -->
  <link rel="shortcut icon" href="assets/images/logo.png" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body>
  <div class="container-scroller">
    <div class="container-fluid page-body-wrapper full-page-wrapper">
      <div class="content-wrapper d-flex align-items-center auth px-0">
        <div class="row w-100 mx-0">
          <div class="col-lg-4 mx-auto">
            <div class="auth-form-light text-left py-5 px-4 px-sm-5 shadow-lg rounded">
              <div class="brand-logo text-center mb-4">
                <img src="assets/images/logo-bapintar.png" alt="logo Bapintar" style="width: 250px; height: auto;">
              </div>
              
              <?php if(!empty($error)): ?>
                  <div class="alert alert-danger text-center p-2 mb-4 mt-3" style="font-size: 0.9rem;"><?= htmlspecialchars($error) ?></div>
              <?php endif; ?>

              <form class="pt-3" method="POST" action="">
                <div class="form-group mb-3">
                  <input type="text" class="form-control form-control-lg" name="username" placeholder="Username / Email" required>
                </div>
                <div class="form-group mb-3">
                  <input type="password" class="form-control form-control-lg" name="password" placeholder="Password" required>
                </div>
                <div class="mt-3 d-grid gap-2 mb-3">
                  <button class="btn btn-block btn-primary btn-lg font-weight-medium auth-form-btn" type="submit">SIGN IN</button>
                </div>
                
                <div class="mt-3 mb-3 text-center">
                    <span class="text-muted small">--- ATAU ---</span>
                </div>
                
                <div class="mt-2 d-grid gap-2">
                  <?php
                    // Buat link otorisasi Google OAuth
                    $google_auth_url = 'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query([
                        'client_id' => $google_client_id,
                        'redirect_uri' => $google_redirect_uri,
                        'response_type' => 'code',
                        'scope' => 'email profile',
                        'access_type' => 'online'
                    ]);
                  ?>
                  <a href="<?= $google_auth_url ?>" class="btn btn-block btn-outline-danger btn-lg font-weight-medium auth-form-btn">
                    <i class="fab fa-google me-2"></i> LOGIN WITH GOOGLE
                  </a>
                </div>
              </form>

            </div>
          </div>
        </div>
      </div>
      <!-- content-wrapper ends -->
    </div>
    <!-- page-body-wrapper ends -->
  </div>
  <!-- container-scroller -->
  <!-- plugins:js -->
  <script src="assets_skydash/vendors/js/vendor.bundle.base.js"></script>
  <!-- endinject -->
  <!-- inject:js -->
  <script src="assets_skydash/js/off-canvas.js"></script>
  <script src="assets_skydash/js/template.js"></script>
  <script src="assets_skydash/js/settings.js"></script>
  <!-- endinject -->
</body>
</html>
