<?php

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

EmployeeAuth::check('manage_ads');

$data = Request::post();

try {

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

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

/* upload image */

$image = null;

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

$stmt = $conn->prepare("

INSERT INTO ads
(title,placement,image,link,ad_code,priority,start_date,end_date,status)

VALUES
(:title,:placement,:image,:link,:code,:priority,:start,:end,:status)

");

$stmt->execute([

':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

]);

$id = $conn->lastInsertId();

Response::success([
'id'=>$id
],"Ad created");

}
catch(Exception $e){

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

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

}
