<?php
require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';

if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json; charset=utf-8');

if (empty($_SESSION['user_id'])) {
    echo json_encode(['success'=>false,'message'=>'Unauthorized']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true) ?: [];

$user_id = (int)$_SESSION['user_id'];
$day_no = max(1, min(30, (int)($input['day_no'] ?? 1)));
$journal_text = trim($input['journal_text'] ?? '');

if ($journal_text === '') {
    echo json_encode(['success'=>false,'message'=>'Journal empty']);
    exit;
}

try {
    $stmt = $pdo->prepare("
        INSERT INTO madhab_journals 
        (user_id, day_no, journal_text)
        VALUES (?, ?, ?)
    ");
    $stmt->execute([$user_id, $day_no, $journal_text]);
    echo json_encode(['success'=>true,'message'=>'Journal saved']);
} catch (Throwable $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}