<?php
/**
 * Secure API for Copyrights (copy_rights)
 * Handles fetching content with integrity verification.
 */
header('Content-Type: application/json; charset=utf-8');
session_start();

require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

if (!isset($_SESSION['userid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit;
}

$db = new App_DB(DBU::$dba_user);
$input = json_decode(file_get_contents('php://input'), true);
$action = $_GET['action'] ?? $input['action'] ?? '';

$salt = "madrasa_secure_salt_2026";

switch ($action) {
    case 'get_content':
        try {
            $sql = "SELECT contents_ur, dua_ur, signature_ur, integrity_hash FROM copy_rights ORDER BY id DESC LIMIT 1";
            $res = $db->getRecordSet($sql);

            if (empty($res)) {
                echo json_encode(['success' => false, 'message' => 'No copyright content found in database.']);
                exit;
            }

            $data = $res[0];
            $concatenated = $data['contents_ur'] . $data['dua_ur'] . $data['signature_ur'];
            $calculated_hash = hash_hmac('sha256', $concatenated, $salt);

            $tamper_detected = ($calculated_hash !== $data['integrity_hash']);

            echo json_encode([
                'success' => true,
                'data' => [
                    'content' => $data['contents_ur'],
                    'dua' => $data['dua_ur'],
                    'signature' => $data['signature_ur'],
                    'tamper_detected' => $tamper_detected
                ]
            ]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        break;

    case 'save_content':
        // For future use or admin updates
        $content = $input['content'] ?? '';
        $dua = $input['dua'] ?? '';
        $signature = $input['signature'] ?? '';

        if (empty($content)) {
            echo json_encode(['success' => false, 'message' => 'Content cannot be empty.']);
            exit;
        }

        $new_hash = hash_hmac('sha256', $content . $dua . $signature, $salt);

        try {
            $sql = "INSERT INTO copy_rights (contents_ur, dua_ur, signature_ur, integrity_hash) VALUES (?, ?, ?, ?)";
            $db->dbQuery($sql, [$content, $dua, $signature, $new_hash]);
            echo json_encode(['success' => true, 'message' => 'Content updated successfully with new integrity hash.']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Update error: ' . $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action.']);
        break;
}
?>