<?php
$config = require __DIR__ . '/../includes/config.php';
$dir = $config['upload_dir'];
if(!is_dir($dir)) mkdir($dir,0755,true);

$raw = $_POST['photo_data'] ?? '';
header('Content-Type: application/json');
if(!$raw) { echo json_encode(['success'=>false]); exit; }

if(preg_match('/^data:image\\/(png|jpeg|jpg);base64,/', $raw, $m)){
  $ext = $m[1]=='png'?'png':'jpg';
  $data = base64_decode(substr($raw,strpos($raw, ',')+1));
  $fname = 'photo_'.time().'_'.bin2hex(random_bytes(5)).".$ext";
  file_put_contents($dir.'/'.$fname,$data);
  echo json_encode(['success'=>true,'path'=>$config['upload_base'].'/'.$fname]);
}else echo json_encode(['success'=>false]);
