<?php
// /api/towlens/notes.php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

$ROOT = realpath(__DIR__ . '/..');
if (!$ROOT) { http_response_code(500); echo json_encode(['error'=>'Server error']); exit; }

$config = require $ROOT . '/lib/config.php';
require $ROOT . '/lib/db.php';

if (!($pdo instanceof PDO)) { http_response_code(500); echo json_encode(['error'=>'DB unavailable']); exit; }
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

function jresp($d,$s=200){ http_response_code($s); echo json_encode($d,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }

$token = $_POST['token'] ?? '';
$notes = trim($_POST['notes'] ?? '');

if ($notes === '') {
    jresp(['error' => 'No notes'], 400);
}

$isShareToken  = preg_match('/^[a-f0-9]{64}$/', $token);
$isLegacyToken = preg_match('/^[a-f0-9-]{36}$/i', $token);

$reqId   = null;
$shareId = null;

if ($isShareToken) {
    $stmt = $pdo->prepare("
      SELECT s.id AS share_id, r.id AS request_id, s.expires_at, s.status
      FROM request_shares s
      JOIN requests r ON r.id = s.request_id
      WHERE s.token = ?
      LIMIT 1
    ");
    $stmt->execute([$token]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) jresp(['error'=>'Invalid link'],400);

    // Expiry check
    if (!empty($row['expires_at']) && $row['expires_at'] < date('Y-m-d H:i:s')) {
        $pdo->prepare("UPDATE request_shares SET status='expired' WHERE id=?")
            ->execute([(int)$row['share_id']]);
        jresp(['error'=>'Link expired'],400);
    }
    if (in_array(strtolower($row['status']), ['expired','cancelled'], true)) {
        jresp(['error'=>'Link closed'],400);
    }

    $reqId   = (int)$row['request_id'];
    $shareId = (int)$row['share_id'];
} elseif ($isLegacyToken) {
    $stmt = $pdo->prepare("SELECT id FROM requests WHERE token = ? LIMIT 1");
    $stmt->execute([$token]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) jresp(['error'=>'Invalid link'],400);
    $reqId = (int)$row['id'];
} else {
    jresp(['error'=>'Invalid token'],400);
}

// Insert into request_notes if exists
try {
    $pdo->exec("
      CREATE TABLE IF NOT EXISTS request_notes (
        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        request_id INT UNSIGNED NOT NULL,
        organisation_id INT UNSIGNED NULL,
        company_id INT UNSIGNED NULL,
        notes TEXT NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ");

    $ins = $pdo->prepare("
      INSERT INTO request_notes (request_id, notes)
      VALUES (?, ?)
    ");
    $ins->execute([$reqId, $notes]);
} catch (Throwable $e) {
    // soft fail
}

// Log event
try {
    $pdo->exec("
      CREATE TABLE IF NOT EXISTS towlens_events (
        id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        request_id INT UNSIGNED DEFAULT NULL,
        share_id INT UNSIGNED DEFAULT NULL,
        file_id INT UNSIGNED DEFAULT NULL,
        event_type VARCHAR(50) NOT NULL,
        details TEXT DEFAULT NULL,
        ip VARCHAR(45) DEFAULT NULL,
        user_agent VARCHAR(255) DEFAULT NULL,
        created_by VARCHAR(190) DEFAULT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_req (request_id),
        INDEX idx_share (share_id),
        INDEX idx_file (file_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ");

    $ev = $pdo->prepare("
      INSERT INTO towlens_events (request_id, share_id, event_type, details, ip, user_agent)
      VALUES (?, ?, 'NOTE_SUBMITTED', ?, ?, ?)
    ");
    $ev->execute([
        $reqId,
        $shareId,
        $notes,
        $_SERVER['REMOTE_ADDR'] ?? null,
        substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 250),
    ]);
} catch (Throwable $e) { /* ignore */ }

jresp(['status'=>'ok']);