<?php
header('Content-Type: application/json');
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']);
    exit;
}

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

switch ($action) {
    case 'get_terms':
        try {
            $sql = "SELECT * FROM rules_and_regulations WHERE sno = 1";
            $res = $db->getRecordSet($sql);
            if (!empty($res)) {
                echo json_encode(['success' => true, 'data' => $res[0]]);
            } else {
                // If no record exists, return empty structure
                echo json_encode(['success' => true, 'data' => ['contents_ur' => '', 'contents_en' => '']]);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error fetching terms: ' . $e->getMessage()]);
        }
        break;

    case 'save_terms':
        $ur = $input['contents_ur'] ?? '';
        $en = $input['contents_en'] ?? '';

        try {
            // Check if record exists
            $exists = $db->getValue("SELECT sno FROM rules_and_regulations WHERE sno = 1");
            if ($exists) {
                $sql = "UPDATE rules_and_regulations SET contents_ur = ?, contents_en = ? WHERE sno = 1";
                $db->dbQuery($sql, [$ur, $en]);
            } else {
                $sql = "INSERT INTO rules_and_regulations (sno, contents_ur, contents_en) VALUES (1, ?, ?)";
                $db->dbQuery($sql, [$ur, $en]);
            }
            echo json_encode(['success' => true, 'message' => 'اصولی قواعد و ضوابط کامیابی سے محفوظ کر لیے گئے ہیں۔']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'محفوظ کرنے میں غلطی: ' . $e->getMessage()]);
        }
        break;

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