<?php
declare(strict_types=1);
require_once dirname(__DIR__) . '/sonocamara-private/bootstrap.php';
header('Content-Type: application/json; charset=utf-8');
try {
  if($_SERVER['REQUEST_METHOD']!=='POST') throw new RuntimeException('Método no permitido.');
  verify_csrf($_POST['csrf']??null); if(trim((string)($_POST['website']??''))!=='') throw new RuntimeException('Solicitud rechazada.');
  $pdo=db(); if(!$pdo) throw new RuntimeException('La base de datos todavía no ha sido configurada.');
  $name=trim((string)($_POST['author_name']??''));$email=trim((string)($_POST['author_email']??''));$message=trim((string)($_POST['message']??''));$video=valid_video_url($_POST['video_url']??null);
  if($name===''||mb_strlen($name)>cfg('limits.name_max')) throw new RuntimeException('Revisa el nombre ingresado.');
  if($email!==''&&(!filter_var($email,FILTER_VALIDATE_EMAIL)||mb_strlen($email)>cfg('limits.email_max'))) throw new RuntimeException('El correo no es válido.');
  $ml=mb_strlen($message); if($ml<cfg('limits.message_min')||$ml>cfg('limits.message_max')) throw new RuntimeException('El recuerdo debe contener entre 20 y 1,500 caracteres.');
  $st=$pdo->prepare("SELECT COUNT(*) FROM memories WHERE ip_address=:ip AND created_at>=DATE_SUB(NOW(), INTERVAL :mins MINUTE)");$st->bindValue(':ip',client_ip());$st->bindValue(':mins',(int)cfg('limits.rate_limit_minutes'),PDO::PARAM_INT);$st->execute();if((int)$st->fetchColumn()>=(int)cfg('limits.rate_limit_count'))throw new RuntimeException('Se alcanzó el límite temporal de envíos. Inténtalo más tarde.');
  $public=random_id();$slug=slugify($name).'-'.substr($public,0,8);$avatar=uploaded_image($_FILES['avatar']??[],'avatar',$public);$photo=uploaded_image($_FILES['memory_image']??[],'memory',$public);
  $data=array_merge(['public_id'=>$public,'slug'=>$slug,'author_name'=>$name,'public_name'=>public_name($name),'email'=>$email?:null,'message'=>$message,'video'=>$video,'ip'=>client_ip()],$avatar,$photo);
  $st=$pdo->prepare("INSERT INTO memories(public_id,slug,author_name,public_name,author_email,message,avatar_path,image_path,image_thumb_path,video_url,status,ip_address) VALUES(:public_id,:slug,:author_name,:public_name,:email,:message,:avatar_path,:image_path,:image_thumb_path,:video,'pending',:ip)");
  $st->execute(['public_id'=>$data['public_id'],'slug'=>$data['slug'],'author_name'=>$data['author_name'],'public_name'=>$data['public_name'],'email'=>$data['email'],'message'=>$data['message'],'avatar_path'=>$data['avatar_path']??null,'image_path'=>$data['image_path']??null,'image_thumb_path'=>$data['image_thumb_path']??null,'video'=>$data['video'],'ip'=>$data['ip']]);
  $data['id']=(int)$pdo->lastInsertId();notify_new_memory($data);
  echo json_encode(['ok'=>true,'message'=>'Recuerdo recibido. Será revisado antes de publicarse.'],JSON_UNESCAPED_UNICODE);
} catch(Throwable $e){ http_response_code(422); echo json_encode(['ok'=>false,'message'=>$e->getMessage()],JSON_UNESCAPED_UNICODE); }
