<?php

require_once '../../core/api_bootstrap.php';
require_once '../../core/employee_auth.php';

EmployeeAuth::check('manage_ads');

$data = Request::post();

try {

Validator::required($data,[
'id',
'title',
'placement'
]);

$db = new Database();
$conn = $db->connect();

/* check ad exists */

$stmt = $conn->prepare("
SELECT id,image
FROM ads
WHERE id=:id
LIMIT 1
");

$stmt->execute([
':id'=>$data['id']
]);

$ad = $stmt->fetch();

if(!$ad){
Response::error("Ad not found");
}

/* image upload */

$image = $ad['image'];

if(isset($_FILES['image'])){
$image = Upload::image('image','ads');
}

/* update ad */

$stmt = $conn->prepare("

UPDATE ads
SET
title=:title,
placement=:placement,
image=:image,
link=:link,
ad_code=:code,
priority=:priority,
start_date=:start,
end_date=:end,
status=:status

WHERE id=:id

");

$stmt->execute([

':id'=>$data['id'],
':title'=>$data['title'],
':placement'=>$data['placement'],
':image'=>$image,
':link'=>$data['link'] ?? null,
':code'=>$data['ad_code'] ?? null,
':priority'=>$data['priority'] ?? 1,
':start'=>$data['start_date'] ?? null,
':end'=>$data['end_date'] ?? null,
':status'=>$data['status'] ?? 1

]);

Response::success([],"Ad updated successfully");

}
catch(Exception $e){

Logger::log("system.log",$e->getMessage());

Response::error("Server error",500);

}
