<?php
require_once __DIR__ . '/../init.php';
require_once PROJECT_ROOT . '/backend/controllers/common_function.php';
require_once PROJECT_ROOT . '/backend/controllers/db_select_helper.php';
class UserLoginDevicesController
{
    private $conn;
    private $table = "user_login_devices";
    private $pk = "IDToken";

    public function __construct($conn)
    {
        $this->conn = $conn;
    }

    // --- Insert session baru ---
    public function UpdateSession($post)
    {
        try {
            $IDUser = intval($post['IDUser']);
            $DeviceUUID = $this->conn->real_escape_string($post['DeviceUUID']);
            $DevicePlatform = $this->conn->real_escape_string($post['DevicePlatform'] ?? 'Unknown');
            $DeviceName = $this->conn->real_escape_string($post['DeviceName'] ?? '');
            $IPAddress = $this->conn->real_escape_string($post['IPAddress'] ?? '');
            $UserAgent = $this->conn->real_escape_string($post['UserAgent'] ?? '');
            $GPS = $this->conn->real_escape_string($post['GPS'] ?? '');
            $GPS_Lat = isset($post['GPS_Lat']) ? floatval($post['GPS_Lat']) : null;
            $GPS_Lng = isset($post['GPS_Lng']) ? floatval($post['GPS_Lng']) : null;
            $Token = bin2hex(random_bytes(32));
            $IsActive = 1;

            $sql = "
            INSERT INTO {$this->table} 
                (IDUser, DeviceUUID, DevicePlatform, DeviceName, IPAddress, UserAgent, GPS, GPS_Lat, GPS_Lng, Token, ExpiryDate, IsActive)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW() + INTERVAL 7 DAY, ?)
            ON DUPLICATE KEY UPDATE
                DevicePlatform = VALUES(DevicePlatform),
                DeviceName = VALUES(DeviceName),
                IPAddress = VALUES(IPAddress),
                UserAgent = VALUES(UserAgent),
                GPS = VALUES(GPS),
                GPS_Lat = VALUES(GPS_Lat),
                GPS_Lng = VALUES(GPS_Lng),
                Token = VALUES(Token),
                ExpiryDate = NOW() + INTERVAL 7 DAY,
                IsActive = VALUES(IsActive),
                UpdatedAt = CURRENT_TIMESTAMP
        ";

            $stmt = $this->conn->prepare($sql);
            $stmt->bind_param(
                "issssssddsi",
                $IDUser,
                $DeviceUUID,
                $DevicePlatform,
                $DeviceName,
                $IPAddress,
                $UserAgent,
                $GPS,
                $GPS_Lat,
                $GPS_Lng,
                $Token,
                $IsActive
            );

            $stmt->execute();

            return [
                "Status" => 1,
                "Keterangan" => "Login session updated",
                "Token" => $Token
            ];
        } catch (Exception $e) {
            return [
                "Status" => 0,
                "Keterangan" => $e->getMessage()
            ];
        }
    }


    // --- Check apakah token masih aktif dan valid ---
    public function check($post)
    {
        try {
            $IDUser = intval($post['IDUser']);
            $Token = $this->conn->real_escape_string($post['Token']);

            $di = json_decode($post['device_info'], true);
            $DeviceUUID = $this->conn->real_escape_string($di['device_id']) ?? null;

            // --- Cek session valid ---
            $sql = "SELECT * FROM {$this->table} 
                WHERE IDUser = ? AND Token = ? AND DeviceUUID = ? 
                AND IsActive = 1 AND ExpiryDate > NOW()";
            $stmt = $this->conn->prepare($sql);
            $stmt->bind_param("iss", $IDUser, $Token, $DeviceUUID);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 0) {
                return ["Status" => 0, "Keterangan" => "Invalid or expired session"];
            }

            // --- Update last checked time ---
            $updateSql = "UPDATE {$this->table} 
                      SET UpdatedAt = NOW() 
                      WHERE IDUser = ? AND Token = ? AND DeviceUUID = ?";
            $updateStmt = $this->conn->prepare($updateSql);
            $updateStmt->bind_param("iss", $IDUser, $Token, $DeviceUUID);
            $updateStmt->execute();

            // --- Ambil detail user dan group-nya ---
            $userSql = "SELECT 
                        u.IDUser, 
                        u.NamaLengkap AS Nama, 
                        u.Email, 
                        u.Avatar,
                        IFNULL(g.NamaGroup,'-') AS `NamaGroup`
                    FROM user u
                    LEFT JOIN user_group g ON u.IDGroup = g.IDUserGroup
                    WHERE u.IDUser = ?";
            $userStmt = $this->conn->prepare($userSql);
            $userStmt->bind_param("i", $IDUser);
            $userStmt->execute();
            $userRes = $userStmt->get_result();
            $userData = $userRes->fetch_assoc();

            return [
                "Status" => 1,
                "Keterangan" => "",
                "ID" => $IDUser,
                "listUser" => $userData
            ];

        } catch (Exception $e) {
            return ["Status" => 0, "Keterangan" => "Check Error: " . $e->getMessage()];
        }
    }


    // --- Revoke / logout satu sesi ---
    public function revoke($post)
    {
        try {
            $Token = $this->conn->real_escape_string($post['Token']);
            $DeviceUUID = $this->conn->real_escape_string($post['DeviceUUID']);

            $sql = "UPDATE $this->table SET IsActive = 0 WHERE Token = '$Token' AND DeviceUUID = '$DeviceUUID' AND UpdatedAt = NOW()";
            $this->conn->query($sql);
            return ["Status" => 1, "Keterangan" => "Session revoked"];
        } catch (Exception $e) {
            return ["Status" => 0, "Keterangan" => "Revoke Error: " . $e->getMessage()];
        }
    }
    // --- Logout Remove Session ---
    public function logout($post)
    {
        try {
            $Token = $post['Token'];
            $IDUser = $post['IDUser'];

            $sql = "DELETE FROM {$this->table} WHERE Token = ? AND IDUser = ?";
            $stmt = $this->conn->prepare($sql);

            if (!$stmt) {
                throw new Exception("Prepare failed: " . $this->conn->error);
            }

            $stmt->bind_param("si", $Token, $IDUser);

            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }

            $stmt->close();

            return [
                "Status" => 1,
                "Keterangan" => ""
            ];
        } catch (Exception $e) {
            return [
                "Status" => 0,
                "Keterangan" => "Revoke Error: " . $e->getMessage()
            ];
        }
    }

}
