<?php
// ============================================================
// api/training.php — Training Materials API
// Training data is stored in a 'training_materials' table in DB.
// Table is created on first use if it doesn't exist yet. Once it
// has at least one row, that row's content is shown; until then,
// a helpful default welcome message is shown instead.
// ============================================================
session_start();
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

if (!isset($_SESSION['oms_user'])) {
    http_response_code(401); echo json_encode(['status'=>'error','msg'=>'Not authenticated']); exit;
}

$host = 'database.xhost.co.in';
$db   = 'db_iqpj6ze2cf';
$user = 'db_iqpj6ze2cf';
$pass = 'O*9Mp;%5PPDyv8oD';

try {
    $pdo = new PDO("pgsql:host=$host;port=5432;dbname=$db", $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);

    $input2  = json_decode(file_get_contents('php://input'), true) ?? [];
    $action2 = $input2['action'] ?? $_GET['action'] ?? 'get_training';

    // FIX: table is now created unconditionally, up front, before any action check.
    // Previously this only ran inside the save_material branch, but that branch was
    // never reached — the table-missing check above it returned early with a hardcoded
    // fallback (still status=success) whenever the table didn't exist yet, silently
    // discarding every save attempt.
    $pdo->exec("CREATE TABLE IF NOT EXISTS training_materials (
        id SERIAL PRIMARY KEY,
        header VARCHAR(200),
        subheading VARCHAR(200),
        bodytext TEXT,
        image TEXT DEFAULT '',
        video TEXT DEFAULT '',
        created_at TIMESTAMP DEFAULT NOW(),
        updated_at TIMESTAMP DEFAULT NOW()
    )");

    // ── SAVE ──
    if ($action2 === 'save_material') {
        if (!in_array($_SESSION['oms_user']['role'], ['admin','writer'])) {
            http_response_code(403); echo json_encode(['status'=>'error','msg'=>'Not authorized']); exit;
        }
        $header = trim($input2['header']     ?? '');
        $sub    = trim($input2['subheading'] ?? '');
        $body   = trim($input2['bodytext']   ?? '');
        $image  = trim($input2['image']      ?? '');
        $video  = trim($input2['video']      ?? '');
        if (!$header) { echo json_encode(['status'=>'error','msg'=>'Header is required']); exit; }
        $stmt = $pdo->prepare("INSERT INTO training_materials (header, subheading, bodytext, image, video) VALUES (?,?,?,?,?)");
        $stmt->execute([$header, $sub, $body, $image, $video]);
        echo json_encode(['status'=>'success','msg'=>'Training material saved']);
        exit;
    }

    // ── DELETE (added for symmetry — wasn't present before, safe additive endpoint) ──
    if ($action2 === 'delete_material') {
        if (!in_array($_SESSION['oms_user']['role'], ['admin','writer'])) {
            http_response_code(403); echo json_encode(['status'=>'error','msg'=>'Not authorized']); exit;
        }
        $id = intval($input2['id'] ?? 0);
        if (!$id) { echo json_encode(['status'=>'error','msg'=>'id is required']); exit; }
        $stmt = $pdo->prepare("DELETE FROM training_materials WHERE id = $1");
        $stmt->execute([$id]);
        echo json_encode(['status'=>'success','msg'=>'Training material deleted']);
        exit;
    }

    // ── GET ──
    $countRow = $pdo->query("SELECT COUNT(*) AS c FROM training_materials")->fetch();
    $hasRows  = ((int)($countRow['c'] ?? 0)) > 0;

    if (!$hasRows) {
        // Table exists but genuinely empty (first-ever run, nothing saved yet) — show the
        // same helpful default as before, purely as a placeholder, not a save-blocking bug.
        echo json_encode([
            'status' => 'success',
            'data'   => [
                [
                    'header'      => 'Welcome to Training',
                    'subheadings' => [
                        ['sub' => 'How to use this section', 'body' => "Training materials will appear here once your admin adds them.\n\nClick \"Add Material\" above to create your first entry — it will show up here immediately after saving."]
                    ],
                    'image' => '',
                    'video' => ''
                ],
                [
                    'header'      => 'Agent Guide',
                    'subheadings' => [
                        ['sub' => 'How to update order status', 'body' => "1. Go to Agent View tab\n2. Select today's date range\n3. Click on any order to open it\n4. Update the Status (Done/Cancel/NP/Busy etc.)\n5. Add a remark if needed\n6. Click Save Changes\n\nThe status will be saved immediately to the database."],
                        ['sub' => 'Status meanings', 'body' => "Done — Customer confirmed the order\nCancel — Customer cancelled\nNP — No pickup (phone not picked up)\nBusy — Customer was busy, call later\nSO — Switch off (phone switched off)\nNI — Not interested\nHold — Put on hold\nAdd. Change — Address change requested\nInvalid — Invalid/wrong number"]
                    ],
                    'image' => '',
                    'video' => ''
                ]
            ]
        ]);
        exit;
    }

    // Table has real content — fetch and group by header
    $rows = $pdo->query("SELECT id, header, subheading, bodytext, image, video FROM training_materials ORDER BY id")->fetchAll();

    $groups = []; $groupOrder = [];
    foreach ($rows as $row) {
        $header = trim($row['header'] ?? '');
        $sub    = trim($row['subheading'] ?? '');
        $body   = trim($row['bodytext']   ?? '');
        $image  = trim($row['image']      ?? '');
        $video  = trim($row['video']      ?? '');
        $key    = $header ?: ('__row_'.$row['id']);
        if (!isset($groups[$key])) {
            $groups[$key] = ['header'=>$header,'subheadings'=>[],'image'=>$image,'video'=>$video];
            $groupOrder[] = $key;
        }
        if ($sub || $body) $groups[$key]['subheadings'][] = ['sub'=>$sub,'body'=>$body];
        if ($image) $groups[$key]['image'] = $image;
        if ($video) $groups[$key]['video'] = $video;
    }

    $data = array_map(fn($k) => $groups[$k], $groupOrder);
    echo json_encode(['status' => 'success', 'data' => $data]);

} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'msg' => 'DB error: '.$e->getMessage()]);
}