<?php
header('Content-Type: application/json; charset=utf-8');header('Access-Control-Allow-Origin: *');
$cfg=require __DIR__.'/../config/config.php';
try{
  $pdo=new PDO("mysql:host={$cfg['db_host']};dbname={$cfg['db_name']};charset=utf8mb4",$cfg['db_user'],$cfg['db_pass'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,PDO::ATTR_EMULATE_PREPARES=>false]);
  $schema=file_get_contents(__DIR__.'/../database/schema.sql');if($schema===false)throw new RuntimeException('schema.sql not found');$pdo->exec($schema);
  require __DIR__.'/../src/auth_schema.php';ensure_auth_schema($pdo);
  $required=['admins','users','app_settings','banners','donors','blood_requests','campaigns','feature_cards'];$existing=[];
  foreach($required as $table){$s=$pdo->prepare('SHOW TABLES LIKE ?');$s->execute([$table]);$existing[$table]=(bool)$s->fetchColumn();}
  echo json_encode(['ok'=>!in_array(false,$existing,true),'message'=>'Database repair completed','tables'=>$existing,'auth_ready'=>true,'next'=>'Open index.php?route=health then delete repair.php.'],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
}catch(Throwable $e){http_response_code(500);echo json_encode(['ok'=>false,'message'=>'Database repair failed','error'=>$e->getMessage()],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);}
