%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home2/rezakur1/ternakdolar.my.id/Ternak-Dolar/
Upload File :
Create Path :
Current File : /home2/rezakur1/ternakdolar.my.id/Ternak-Dolar/api.php

<?php
/**
 * REST API Endpoint — YouTube Shorts Manager
 * Database: MySQL (db_ternakdolar)
 */

require_once __DIR__ . '/auth.php';

$action = $_GET['action'] ?? '';

// ============================================================
// GET: Ambil 1 video random (PUBLIC — tanpa auth)
// ============================================================
if ($action === 'random') {
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') jsonError('Method not allowed', 405);

    try {
        $db = getDB();

        $categoryId = $_GET['category_id'] ?? '';

        $sql    = "SELECT id, video_id, title, link_shorts FROM videos WHERE is_copied = 0";
        $params = [];

        if ($categoryId !== '' && $categoryId !== 'all') {
            $sql .= " AND category_id = :category_id";
            $params[':category_id'] = (int) $categoryId;
        }

        $sql .= " ORDER BY RAND() LIMIT 1";

        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $video = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($video) {
            jsonResponse(['video' => $video]);
        } else {
            // Cek apakah memang tidak ada video sama sekali atau semua sudah disalin
            $checkSql = "SELECT COUNT(*) as total FROM videos";
            $checkParams = [];
            if ($categoryId !== '' && $categoryId !== 'all') {
                $checkSql .= " WHERE category_id = :category_id";
                $checkParams[':category_id'] = (int) $categoryId;
            }
            $checkStmt = $db->prepare($checkSql);
            $checkStmt->execute($checkParams);
            $total = (int) $checkStmt->fetch(PDO::FETCH_ASSOC)['total'];

            if ($total > 0) {
                jsonError('Semua link sudah pernah disalin. Silakan reset status untuk mengulang.', 404);
            } else {
                jsonError('Belum ada video tersedia.', 404);
            }
        }
    } catch (PDOException $e) {
        jsonError('Database error: ' . $e->getMessage(), 500);
    }
    exit;
}

// ============================================================
// POST: Tandai video sudah disalin (PUBLIC — tanpa auth)
// ============================================================
if ($action === 'mark_copied') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonError('Method not allowed', 405);

    $body = getRequestBody();
    $videoId = $body['video_id'] ?? '';

    if (empty($videoId)) jsonError('video_id wajib diisi.');

    try {
        $db = getDB();
        $stmt = $db->prepare('
            UPDATE videos
            SET is_copied = 1, copied_at = :copied_at
            WHERE video_id = :video_id AND is_copied = 0
        ');
        $stmt->execute([
            ':copied_at' => date('Y-m-d H:i:s'),
            ':video_id'  => $videoId,
        ]);

        jsonResponse(['updated' => $stmt->rowCount()]);
    } catch (PDOException $e) {
        jsonError('Gagal update: ' . $e->getMessage(), 500);
    }
    exit;
}

// ============================================================
// GET: Ambil daftar referensi/kategori (PUBLIC — tanpa auth)
// ============================================================
if ($action === 'referensi') {
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') jsonError('Method not allowed', 405);

    try {
        $db = getDB();
        $stmt = $db->query('
            SELECT c.id, c.name, c.color,
                   COUNT(v.id) AS video_count
            FROM categories c
            LEFT JOIN videos v ON v.category_id = c.id
            GROUP BY c.id
            ORDER BY c.name ASC
        ');
        $rows = $stmt->fetchAll();

        foreach ($rows as &$row) {
            $row['id'] = (int) $row['id'];
            $row['video_count'] = (int) $row['video_count'];
        }

        jsonResponse(['success' => true, 'data' => $rows]);

    } catch (PDOException $e) {
        jsonError('Gagal memuat referensi: ' . $e->getMessage(), 500);
    }
    exit;
}

// Auth guard — semua API selain random, mark_copied & referensi butuh login
requireAuthAPI();
$method = $_SERVER['REQUEST_METHOD'];

switch ($action) {

    // ============================================================
    // GET: Ambil semua video (JOIN kategori)
    // ============================================================
    case 'list':
        if ($method !== 'GET') jsonError('Method not allowed', 405);

        try {
            $db = getDB();

            $categoryId = $_GET['category_id'] ?? '';
            $search     = trim($_GET['search'] ?? '');
            $status     = $_GET['status'] ?? 'all';
            $page       = max(1, (int) ($_GET['page'] ?? 1));
            $perPage    = max(1, min(200, (int) ($_GET['per_page'] ?? 50)));

            $where  = [];
            $params = [];

            // Category filter
            if ($categoryId !== '' && $categoryId !== 'all') {
                if ($categoryId === 'none') {
                    $where[] = 'v.category_id IS NULL';
                } else {
                    $where[] = 'v.category_id = :category_id';
                    $params[':category_id'] = (int) $categoryId;
                }
            }

            // Search filter
            if ($search !== '') {
                $where[] = 'v.title LIKE :search';
                $params[':search'] = '%' . $search . '%';
            }

            // Status filter
            if ($status === 'copied') {
                $where[] = 'v.is_copied = 1';
            } elseif ($status === 'pending') {
                $where[] = 'v.is_copied = 0';
            } elseif ($status === 'scheduled') {
                $where[] = 'v.schedule_at IS NOT NULL';
            } elseif ($status === 'unscheduled') {
                $where[] = 'v.schedule_at IS NULL';
            }

            $whereSQL = count($where) > 0 ? ' WHERE ' . implode(' AND ', $where) : '';

            // Count total
            $countSQL = 'SELECT COUNT(*) FROM videos v' . $whereSQL;
            $countStmt = $db->prepare($countSQL);
            $countStmt->execute($params);
            $total = (int) $countStmt->fetchColumn();

            // Fetch page
            $offset = ($page - 1) * $perPage;
            // Random seed agar konsisten per sesi browsing
            $seed = $_GET['seed'] ?? '';
            if ($seed !== '') {
                $db->exec('SET @seed = ' . (float) $seed);
                $db->exec('SET @rand = @seed');
            }

            $sql = '
                SELECT v.video_id, v.title, v.link_shorts, v.is_copied, v.copied_at, v.schedule_at,
                       v.category_id, c.name AS category_name, c.color AS category_color
                FROM videos v
                LEFT JOIN categories c ON v.category_id = c.id
            ' . $whereSQL . ' ORDER BY RAND(' . ($seed !== '' ? (float) $seed : '') . ') LIMIT :limit OFFSET :offset';

            $stmt = $db->prepare($sql);
            foreach ($params as $k => $v) {
                $stmt->bindValue($k, $v);
            }
            $stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
            $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
            $stmt->execute();
            $rows = $stmt->fetchAll();

            foreach ($rows as &$row) {
                $row['is_copied'] = (bool) $row['is_copied'];
                $row['category_id'] = $row['category_id'] ? (int) $row['category_id'] : null;
            }

            $totalPages = max(1, (int) ceil($total / $perPage));

            // Global stats (unfiltered)
            $statsStmt = $db->query('
                SELECT
                    COUNT(*) AS total_all,
                    SUM(is_copied = 1) AS total_copied,
                    SUM(schedule_at IS NOT NULL) AS total_scheduled
                FROM videos
            ');
            $stats = $statsStmt->fetch();

            jsonResponse([
                'success'     => true,
                'data'        => $rows,
                'total'       => $total,
                'page'        => $page,
                'per_page'    => $perPage,
                'total_pages' => $totalPages,
                'stats'       => [
                    'total_all'       => (int) $stats['total_all'],
                    'total_copied'    => (int) $stats['total_copied'],
                    'total_scheduled' => (int) $stats['total_scheduled'],
                ],
            ]);

        } catch (PDOException $e) {
            jsonError('Gagal memuat data: ' . $e->getMessage(), 500);
        }
        break;


    // ============================================================
    // POST: Import data JSON (dengan category_id opsional)
    // ============================================================
    case 'import':
        if ($method !== 'POST') jsonError('Method not allowed', 405);

        // Validate content type is JSON
        $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
        if (stripos($contentType, 'application/json') === false) {
            jsonError('Content-Type harus application/json.', 400);
        }

        // Read and validate raw JSON
        $rawInput = file_get_contents('php://input');
        if (empty($rawInput)) {
            jsonError('Request body kosong.', 400);
        }

        // Check raw size (max 10MB)
        if (strlen($rawInput) > 10 * 1024 * 1024) {
            jsonError('Ukuran data terlalu besar. Maksimal 10MB.', 413);
        }

        $body = json_decode($rawInput, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            jsonError('Format JSON tidak valid: ' . json_last_error_msg(), 400);
        }

        if (!is_array($body)) {
            jsonError('Request body harus berupa JSON object.', 400);
        }

        $items      = $body['items'] ?? [];
        $categoryId = $body['category_id'] ?? null;

        // Validate items is array
        if (!is_array($items) || count($items) === 0) {
            jsonError('Data items kosong atau tidak valid.');
        }

        // Limit max items
        $maxItems = defined('MAX_IMPORT_ITEMS') ? MAX_IMPORT_ITEMS : 5000;
        if (count($items) > $maxItems) {
            jsonError("Terlalu banyak items. Maksimal {$maxItems} per import.", 400);
        }

        // Validate each item structure
        $validatedItems = [];
        $errors = [];
        foreach ($items as $index => $item) {
            if (!is_array($item)) {
                $errors[] = "Item #{$index}: bukan object.";
                continue;
            }

            $videoId = trim($item['video_id'] ?? '');
            $title   = trim($item['title'] ?? 'Tanpa Judul');
            $link    = trim($item['link_shorts'] ?? '');

            // Skip empty video_id
            if (empty($videoId)) continue;

            // Validate video_id format (alphanumeric, dash, underscore, max 50 chars)
            if (!preg_match('/^[a-zA-Z0-9_\-]{1,50}$/', $videoId)) {
                $errors[] = "Item #{$index}: video_id format tidak valid.";
                continue;
            }

            // Sanitize title (strip tags, max 500 chars)
            $title = strip_tags($title);
            $title = mb_substr($title, 0, 500);

            // Validate link_shorts if provided
            if (!empty($link)) {
                $link = filter_var($link, FILTER_SANITIZE_URL);
                if (strlen($link) > 500) {
                    $link = mb_substr($link, 0, 500);
                }
            }

            $validatedItems[] = [
                'video_id'    => $videoId,
                'title'       => $title,
                'link_shorts' => $link,
            ];
        }

        if (empty($validatedItems)) {
            $errorMsg = 'Tidak ada data valid untuk diimport.';
            if (!empty($errors)) {
                $errorMsg .= ' Errors: ' . implode('; ', array_slice($errors, 0, 5));
            }
            jsonError($errorMsg);
        }

        // Use validated items instead of raw items
        $items = $validatedItems;

        // Validasi category_id jika dikirim
        if ($categoryId !== null && $categoryId !== '') {
            $categoryId = (int) $categoryId;
            $db = getDB();
            $check = $db->prepare('SELECT id FROM categories WHERE id = :id');
            $check->execute([':id' => $categoryId]);
            if (!$check->fetch()) {
                jsonError('Kategori tidak ditemukan.');
            }
        } else {
            $categoryId = null;
        }

        try {
            $db = getDB();
            $inserted = 0;

            $stmt = $db->prepare('
                INSERT INTO videos (video_id, title, link_shorts, category_id)
                VALUES (:video_id, :title, :link_shorts, :category_id)
                ON DUPLICATE KEY UPDATE title = VALUES(title), category_id = COALESCE(VALUES(category_id), category_id)
            ');

            $db->beginTransaction();

            foreach ($items as $item) {
                $videoId = $item['video_id'] ?? '';
                $title   = $item['title'] ?? 'Tanpa Judul';
                $link    = $item['link_shorts'] ?? '';

                if (empty($videoId)) continue;

                $stmt->execute([
                    ':video_id'    => $videoId,
                    ':title'       => $title,
                    ':link_shorts' => $link,
                    ':category_id' => $categoryId,
                ]);

                if ($stmt->rowCount() === 1) {
                    $inserted++;
                }
            }

            $db->commit();

            jsonResponse([
                'success'  => true,
                'inserted' => $inserted,
                'total'    => count($items),
            ]);

        } catch (PDOException $e) {
            if (isset($db) && $db->inTransaction()) {
                $db->rollBack();
            }
            jsonError('Gagal import: ' . $e->getMessage(), 500);
        }
        break;


    // ============================================================
    // PATCH: Update status copy
    // ============================================================
    case 'copy':
        if ($method !== 'PATCH' && $method !== 'POST') jsonError('Method not allowed', 405);

        $body = getRequestBody();
        $videoId = $body['video_id'] ?? '';

        if (empty($videoId)) jsonError('video_id wajib diisi.');

        try {
            $db = getDB();
            $stmt = $db->prepare('
                UPDATE videos
                SET is_copied = 1, copied_at = :copied_at
                WHERE video_id = :video_id AND is_copied = 0
            ');
            $stmt->execute([
                ':copied_at' => date('Y-m-d H:i:s'),
                ':video_id'  => $videoId,
            ]);

            jsonResponse(['success' => true, 'updated' => $stmt->rowCount()]);

        } catch (PDOException $e) {
            jsonError('Gagal update copy: ' . $e->getMessage(), 500);
        }
        break;


    // ============================================================
    // PATCH: Simpan/update jadwal
    // ============================================================
    case 'schedule':
        if ($method !== 'PATCH' && $method !== 'POST') jsonError('Method not allowed', 405);

        $body = getRequestBody();
        $videoId    = $body['video_id'] ?? '';
        $scheduleAt = $body['schedule_at'] ?? '';

        if (empty($videoId)) jsonError('video_id wajib diisi.');
        if (empty($scheduleAt)) jsonError('schedule_at wajib diisi.');

        $dt = date('Y-m-d H:i:s', strtotime($scheduleAt));

        try {
            $db = getDB();
            $stmt = $db->prepare('
                UPDATE videos
                SET schedule_at = :schedule_at
                WHERE video_id = :video_id
            ');
            $stmt->execute([
                ':schedule_at' => $dt,
                ':video_id'    => $videoId,
            ]);

            jsonResponse(['success' => true, 'updated' => $stmt->rowCount()]);

        } catch (PDOException $e) {
            jsonError('Gagal simpan jadwal: ' . $e->getMessage(), 500);
        }
        break;


    // ============================================================
    // PATCH: Hapus jadwal
    // ============================================================
    case 'delete_schedule':
        if ($method !== 'PATCH' && $method !== 'POST') jsonError('Method not allowed', 405);

        $body = getRequestBody();
        $videoId = $body['video_id'] ?? '';

        if (empty($videoId)) jsonError('video_id wajib diisi.');

        try {
            $db = getDB();
            $stmt = $db->prepare('
                UPDATE videos
                SET schedule_at = NULL
                WHERE video_id = :video_id
            ');
            $stmt->execute([':video_id' => $videoId]);

            jsonResponse(['success' => true, 'updated' => $stmt->rowCount()]);

        } catch (PDOException $e) {
            jsonError('Gagal hapus jadwal: ' . $e->getMessage(), 500);
        }
        break;


    // ============================================================
    // PATCH: Reset semua status copy
    // ============================================================
    case 'reset':
        if ($method !== 'PATCH' && $method !== 'POST') jsonError('Method not allowed', 405);

        try {
            $db = getDB();
            $stmt = $db->query('
                UPDATE videos
                SET is_copied = 0, copied_at = NULL
                WHERE is_copied = 1
            ');

            jsonResponse(['success' => true, 'updated' => $stmt->rowCount()]);

        } catch (PDOException $e) {
            jsonError('Gagal reset: ' . $e->getMessage(), 500);
        }
        break;


    // ============================================================
    // GET: Ambil semua kategori (dengan jumlah video)
    // ============================================================
    case 'categories':
        if ($method !== 'GET') jsonError('Method not allowed', 405);

        try {
            $db = getDB();
            $stmt = $db->query('
                SELECT c.id, c.name, c.color, c.created_at,
                       COUNT(v.id) AS video_count
                FROM categories c
                LEFT JOIN videos v ON v.category_id = c.id
                GROUP BY c.id
                ORDER BY c.name ASC
            ');
            $rows = $stmt->fetchAll();

            foreach ($rows as &$row) {
                $row['id'] = (int) $row['id'];
                $row['video_count'] = (int) $row['video_count'];
            }

            jsonResponse(['success' => true, 'data' => $rows]);

        } catch (PDOException $e) {
            jsonError('Gagal memuat kategori: ' . $e->getMessage(), 500);
        }
        break;


    // ============================================================
    // POST: Tambah kategori baru
    // ============================================================
    case 'category_add':
        if ($method !== 'POST') jsonError('Method not allowed', 405);

        $body  = getRequestBody();
        $name  = trim($body['name'] ?? '');
        $color = trim($body['color'] ?? '#3b82f6');

        if (empty($name)) jsonError('Nama kategori wajib diisi.');
        if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) $color = '#3b82f6';

        try {
            $db = getDB();
            $stmt = $db->prepare('
                INSERT INTO categories (name, color)
                VALUES (:name, :color)
            ');
            $stmt->execute([':name' => $name, ':color' => $color]);

            jsonResponse([
                'success' => true,
                'id'      => (int) $db->lastInsertId(),
                'name'    => $name,
                'color'   => $color,
            ]);

        } catch (PDOException $e) {
            if ($e->getCode() == 23000) {
                jsonError('Kategori "' . $name . '" sudah ada.');
            }
            jsonError('Gagal tambah kategori: ' . $e->getMessage(), 500);
        }
        break;


    // ============================================================
    // PATCH: Edit kategori
    // ============================================================
    case 'category_edit':
        if ($method !== 'PATCH' && $method !== 'POST') jsonError('Method not allowed', 405);

        $body  = getRequestBody();
        $id    = (int) ($body['id'] ?? 0);
        $name  = trim($body['name'] ?? '');
        $color = trim($body['color'] ?? '');

        if ($id <= 0) jsonError('ID kategori tidak valid.');
        if (empty($name)) jsonError('Nama kategori wajib diisi.');
        if (!empty($color) && !preg_match('/^#[0-9a-fA-F]{6}$/', $color)) $color = '#3b82f6';

        try {
            $db = getDB();
            $stmt = $db->prepare('
                UPDATE categories
                SET name = :name, color = :color
                WHERE id = :id
            ');
            $stmt->execute([':name' => $name, ':color' => $color, ':id' => $id]);

            jsonResponse(['success' => true, 'updated' => $stmt->rowCount()]);

        } catch (PDOException $e) {
            if ($e->getCode() == 23000) {
                jsonError('Kategori "' . $name . '" sudah ada.');
            }
            jsonError('Gagal edit kategori: ' . $e->getMessage(), 500);
        }
        break;


    // ============================================================
    // DELETE: Hapus kategori
    // ============================================================
    case 'category_delete':
        if ($method !== 'DELETE' && $method !== 'POST') jsonError('Method not allowed', 405);

        $body = getRequestBody();
        $id   = (int) ($body['id'] ?? 0);

        if ($id <= 0) jsonError('ID kategori tidak valid.');

        try {
            $db = getDB();
            // FK ON DELETE SET NULL — video tetap ada, category_id jadi NULL
            $stmt = $db->prepare('DELETE FROM categories WHERE id = :id');
            $stmt->execute([':id' => $id]);

            jsonResponse(['success' => true, 'deleted' => $stmt->rowCount()]);

        } catch (PDOException $e) {
            jsonError('Gagal hapus kategori: ' . $e->getMessage(), 500);
        }
        break;


    // ============================================================
    // Default
    // ============================================================
    default:
        jsonError('Action tidak ditemukan.', 404);
        break;
}

Zerion Mini Shell 1.0