<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();
if(!isAdmin())jsonResponse(false,'Akses ditolak.');
if(!verifyCsrfToken($_POST['csrf_token']??''))jsonResponse(false,'CSRF Error');
$action=$_POST['action']??'';

// Upload logo
if($action==='upload_logo'){
  $target = $_POST['target'] ?? 'logo';
  if(!in_array($target, ['logo', 'logo_2', 'logo_3'])) jsonResponse(false, 'Target tidak sah.');
  
  $fileKey = $target; // Assuming input name matches target column
  
  if(empty($_FILES[$fileKey]['name'])||$_FILES[$fileKey]['error']===UPLOAD_ERR_NO_FILE)
    jsonResponse(false,'Tiada fail dipilih.');
  if($_FILES[$fileKey]['error']!==UPLOAD_ERR_OK)
    jsonResponse(false,'Ralat upload (kod:'.$_FILES[$fileKey]['error'].')');
  if($_FILES[$fileKey]['size']>3145728)
    jsonResponse(false,'Fail terlalu besar. Maksimum 3MB.');

  // Semak sambungan fail
  $ext=strtolower(pathinfo($_FILES[$fileKey]['name'],PATHINFO_EXTENSION));
  $allowedExt=['jpg','jpeg','png','gif','webp','svg'];
  if(!in_array($ext,$allowedExt))
    jsonResponse(false,'Format tidak disokong. Guna: PNG, JPG, SVG, WEBP. (Ext: '.$ext.')');

  // Semak MIME — lebih toleran untuk SVG
  $allowedMimes=['image/jpeg','image/jpg','image/png','image/gif','image/webp',
                 'image/svg+xml','image/svg','text/xml','application/xml','text/plain'];
  if(function_exists('finfo_open')){
    $finfo=finfo_open(FILEINFO_MIME_TYPE);
    $mime=finfo_file($finfo,$_FILES[$fileKey]['tmp_name']);
    finfo_close($finfo);
    if(!in_array($mime,$allowedMimes)&&$ext!=='svg')
      jsonResponse(false,'Jenis fail tidak disokong ('.$mime.'). Guna PNG, JPG, SVG, WEBP.');
  }

  $dir=UPLOAD_PATH.'logo/';
  if(!is_dir($dir)){mkdir($dir,0777,true);chmod($dir,0777);}
  if(!is_writable($dir))jsonResponse(false,'Direktori tidak boleh ditulis: '.$dir);

  // Padam logo lama
  try{
    $old=$pdo->query("SELECT $target FROM sektor WHERE id=1 LIMIT 1")->fetch();
    if($old&&!empty($old[$target])&&file_exists($dir.$old[$target]))@unlink($dir.$old[$target]);
  }catch(Exception $e){}

  $filename=$target.'_'.time().'_'.uniqid().'.'.$ext;
  if(!move_uploaded_file($_FILES[$fileKey]['tmp_name'],$dir.$filename))
    jsonResponse(false,'Gagal simpan fail ke: '.$dir.$filename);
  @chmod($dir.$filename,0644);

  $pdo->prepare("UPDATE sektor SET $target=? WHERE id=1")->execute([$filename]);
  logActivity('Kemaskini Logo','sektor',1,$target.' dikemaskini: '.$filename);
  jsonResponse(true,'Logo berjaya dikemaskini!',['url'=>UPLOAD_URL.'logo/'.$filename,'filename'=>$filename]);
}

// Padam logo
if($action==='delete_logo'){
  $target = $_POST['target'] ?? 'logo';
  if(!in_array($target, ['logo', 'logo_2', 'logo_3'])) jsonResponse(false, 'Target tidak sah.');
  try{
    $old=$pdo->query("SELECT $target FROM sektor WHERE id=1 LIMIT 1")->fetch();
    if($old&&!empty($old[$target])&&file_exists(UPLOAD_PATH.'logo/'.$old[$target]))
      @unlink(UPLOAD_PATH.'logo/'.$old[$target]);
  }catch(Exception $e){}
  $pdo->prepare("UPDATE sektor SET $target=NULL WHERE id=1")->execute();
  logActivity('Padam Logo','sektor',1,$target.' dipadam');
  jsonResponse(true,'Logo dipadam.');
}

jsonResponse(false,'Tindakan tidak sah. Action: '.$action);
