<?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 ActivityController
{
    private $conn;
    /* private $table = "
         activity A
         LEFT JOIN activity_detail D ON A.IDActivity = D.IDActivity
         LEFT JOIN user U ON A.IDUser = U.IDUser
     ";*/
    private $table = "
        activity A
        LEFT JOIN user U ON A.IDUser = U.IDUser
    ";
    private $pk = "IDActivity";

    /*protected $displayedColumn = [
        'A.IDActivity',
        'A.Tanggal',
        'A.IDUser',
        'U.Username',
        'U.NamaLengkap',
        'A.Activity',
        'A.Device',
        'A.IP',
        'A.Category',
        'A.KodeUnik',
        'D.IDActivityDetail',
        'D.FieldName',
        'D.OldData',
        'D.NewData'
    ];*/
    protected $displayedColumn = [
        'A.IDActivity',
        'A.Tanggal',
        'A.IDUser',
        'U.Username',
        'U.NamaLengkap',
        'A.UserUsed',
        'A.Activity',
        'A.Device',
        'A.IP',
        'A.Category',
        'A.KodeUnik',
    ];

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

    public function select($post)
    {
        return runSelect(
            $this->conn,
            $this->table,
            $this->pk,
            $this->displayedColumn,
            $post
        );
    }

    public function generateActivity($IDUser, $UserUsed, $queryActivity, $Device, $IP, $Category, $KodeUnik)
    {
        try {
            if (empty($queryActivity)) {
                throw new Exception("Parameter activity tidak lengkap");
            }

            // Gunakan transaksi agar insert activity & detail aman
            return runWithTransaction($this->conn, function ($conn) use ($IDUser, $UserUsed, $queryActivity, $Device, $IP, $Category, $KodeUnik) {

                // Data utama dari queryActivity
                $ActivityText = $queryActivity['Activity'] ?? '';
                $listDetailActivity = $queryActivity['listDetailActivity'] ?? [];

                // Insert ke tabel activity
                $sqlActivity = "INSERT INTO activity 
                (Tanggal, IDUser,UserUsed, Activity, Device, IP, Category, KodeUnik)
                VALUES (NOW(), ?, ?, ?, ?, ?, ?, ?)";

                $stmtActivity = $conn->prepare($sqlActivity);
                if (!$stmtActivity) {
                    throw new Exception("Prepare statement gagal (activity): " . $conn->error);
                }

                $stmtActivity->bind_param(
                    "sssssss",
                    $IDUser,
                    $UserUsed,
                    $ActivityText,
                    $Device,
                    $IP,
                    $Category,
                    $KodeUnik
                );

                $stmtActivity->execute();

                if ($stmtActivity->affected_rows <= 0) {
                    throw new Exception("Gagal insert activity utama");
                }

                $IDActivity = $stmtActivity->insert_id;
                $stmtActivity->close();

                // Insert detail activity (jika ada)
                if (!empty($listDetailActivity) && is_array($listDetailActivity)) {

                    /*
                    $sqlDetail = "INSERT INTO activity_detail 
                    (IDActivity, FieldName, OldData, NewData)
                    VALUES (?, ?, ?, ?)";

                    $stmtDetail = $conn->prepare($sqlDetail);
                    if (!$stmtDetail) {
                        throw new Exception("Prepare statement gagal (activity_detail): " . $conn->error);
                    }

                    foreach ($listDetailActivity as $detail) {
                        $FieldName = $detail['FieldName'] ?? null;
                        $OldData = $detail['OldData'] ?? null;
                        $NewData = $detail['NewData'] ?? null;

                        $stmtDetail->bind_param("isss", $IDActivity, $FieldName, $OldData, $NewData);
                        $stmtDetail->execute();
                    }

                    $stmtDetail->close();
                    */

                    $values = [];
                    $params = [];
                    foreach ($listDetailActivity as $detail) {
                        $values[] = "(?, ?, ?, ?)";
                        $params[] = $IDActivity;
                        $params[] = $detail['FieldName'] ?? null;
                        $params[] = $detail['OldData'] ?? null;
                        $params[] = $detail['NewData'] ?? null;
                    }

                    $sqlDetail = "INSERT INTO activity_detail (IDActivity, FieldName, OldData, NewData) VALUES " . implode(',', $values);
                    $stmtDetail = $conn->prepare($sqlDetail);
                    if (!$stmtDetail) {
                        throw new Exception("Prepare statement gagal (activity_detail): " . $conn->error);
                    }

                    $types = str_repeat('isss', count($listDetailActivity));
                    $stmtDetail->bind_param($types, ...$params);
                    $stmtDetail->execute();
                    $stmtDetail->close();

                }

                return [
                    "Status" => 1,
                    "Keterangan" => "Activity berhasil dicatat",
                    "IDActivity" => $IDActivity
                ];
            });
        } catch (Exception $e) {
            return [
                "Status" => 0,
                "Keterangan" => $e->getMessage()
            ];
        }
    }

}
?>