<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();

// Anyone logged in can access, but canManageUnit will restrict actions

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$currentUserUnit = currentUnitId();
$isSuper = isSuperAdmin();

// Helper to check if user can manage a specific unit's links
function canManageUnit($targetUnitId) {
    global $isSuper, $currentUserUnit;
    if ($isSuper) return true;
    return $targetUnitId && $targetUnitId == $currentUserUnit;
}

if ($action === 'get') {
    $id = intval($_GET['id'] ?? 0);
    $stmt = $pdo->prepare("SELECT * FROM links WHERE id=?");
    $stmt->execute([$id]);
    $link = $stmt->fetch();
    if (!$link) jsonResponse(false, 'Link tidak dijumpai.');
    
    // Check access
    if (!canManageUnit($link['unit_id'])) jsonResponse(false, 'Akses ditolak untuk unit ini.');
    
    // Add logo URL if exists
    if ($link['logo']) {
        $link['logo_url'] = UPLOAD_URL . 'links/' . $link['logo'];
    }
    
    jsonResponse(true, '', $link);
}

if ($action === 'delete') {
    if (!verifyCsrfToken($_GET['csrf'] ?? '')) jsonResponse(false, 'CSRF Error');
    $id = intval($_GET['id'] ?? 0);
    
    $stmt = $pdo->prepare("SELECT unit_id, logo FROM links WHERE id=?");
    $stmt->execute([$id]);
    $link = $stmt->fetch();
    if (!$link) jsonResponse(false, 'Link tidak dijumpai.');
    
    if (!canManageUnit($link['unit_id'])) jsonResponse(false, 'Akses ditolak.');
    
    // Delete logo file if exists
    if ($link['logo']) {
        deleteFile('links/' . $link['logo']);
    }
    
    $pdo->prepare("DELETE FROM links WHERE id=?")->execute([$id]);
    jsonResponse(true, 'Link berjaya dipadam.');
}

if ($action === 'toggle_awam') {
    if (!verifyCsrfToken($_GET['csrf'] ?? '')) jsonResponse(false, 'CSRF Error');
    $id = intval($_GET['id'] ?? 0);
    
    $stmt = $pdo->prepare("SELECT unit_id, awam FROM links WHERE id=?");
    $stmt->execute([$id]);
    $link = $stmt->fetch();
    if (!$link) jsonResponse(false, 'Link tidak dijumpai.');
    
    if (!canManageUnit($link['unit_id'])) jsonResponse(false, 'Akses ditolak.');
    
    $pdo->prepare("UPDATE links SET awam=NOT awam WHERE id=?")->execute([$id]);
    $newVal = $link['awam'] ? 0 : 1;
    jsonResponse(true, $newVal ? 'Link kini dipaparkan di halaman awam.' : 'Link kini disembunyikan dari halaman awam.', ['awam' => $newVal]);
}

if ($action === 'save') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) jsonResponse(false, 'CSRF Error');
    
    $id = intval($_POST['link_id'] ?? 0);
    $unit_id = intval($_POST['unit_id'] ?? 0);
    $subunit_id = !empty($_POST['subunit_id']) ? intval($_POST['subunit_id']) : null;
    $nama = sanitize($_POST['link_nama'] ?? '');
    $url = sanitize($_POST['link_url'] ?? '');
    $ikon = sanitize($_POST['link_ikon'] ?? 'fas fa-link');
    $warna = sanitize($_POST['link_warna'] ?? '#0d6efd');
    $deskripsi = sanitize($_POST['link_desc'] ?? '');
    $awam = isset($_POST['link_awam']) ? 1 : 0;

    if (!$unit_id) jsonResponse(false, 'Unit ID diperlukan.');
    if (!canManageUnit($unit_id)) jsonResponse(false, 'Akses ditolak untuk unit ini.');
    
    // Handle logo upload
    $logoFilename = null;
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] !== UPLOAD_ERR_NO_FILE) {
        $upload = uploadImage($_FILES['logo'], 'links');
        if (!$upload['success']) jsonResponse(false, $upload['message']);
        $logoFilename = $upload['filename'];
    }

    if ($id) {
        // Edit existing
        $stmt = $pdo->prepare("SELECT unit_id, logo FROM links WHERE id=?");
        $stmt->execute([$id]);
        $existing = $stmt->fetch();
        if (!$existing) jsonResponse(false, 'Link tidak dijumpai.');
        if (!canManageUnit($existing['unit_id'])) jsonResponse(false, 'Akses ditolak.');

        $sql = "UPDATE links SET nama=?, url=?, ikon=?, warna=?, deskripsi=?, awam=?, subunit_id=?";
        $params = [$nama, $url, $ikon, $warna, $deskripsi, $awam, $subunit_id];
        
        if ($logoFilename) {
            $sql .= ", logo=?";
            $params[] = $logoFilename;
            // Delete old logo
            if ($existing['logo']) deleteFile('links/' . $existing['logo']);
        }
        
        $sql .= " WHERE id=?";
        $params[] = $id;
        
        $pdo->prepare($sql)->execute($params);
        jsonResponse(true, 'Link berjaya dikemaskini.');
    } else {
        // Add new
        $stmt = $pdo->prepare("INSERT INTO links (unit_id, subunit_id, nama, url, ikon, logo, warna, deskripsi, awam, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$unit_id, $subunit_id, $nama, $url, $ikon, $logoFilename, $warna, $deskripsi, $awam, currentUserId()]);
        jsonResponse(true, 'Link berjaya ditambah.');
    }
}

jsonResponse(false, 'Tindakan tidak sah.');
