<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

include("../includes/db_connection.php");
include("../includes/auth.php");

$id = intval($_POST['id'] ?? 0);

$client_id = intval($_POST['client_id']);
$standard = $_POST['standard'];
$number = $_POST['number'];
$scope = $_POST['scope'] ?? '';
$accreditation = $_POST['accreditation'] ?? '';
$rdate = $_POST['rdate'];
$validity = intval($_POST['validity_years']);
$status = $_POST['status'];

/* Expiry */
$expiry = new DateTime($rdate);
$expiry->modify("+$validity year");
$expiry->modify("-1 day");
$edate = $expiry->format("Y-m-d");

/* Surveillance */
$first_surveillance = NULL;
$second_surveillance = NULL;

if($validity==3){
$f=new DateTime($rdate);
$f->modify("+1 year -1 day");
$first_surveillance=$f->format("Y-m-d");

$s=new DateTime($rdate);
$s->modify("+2 year -1 day");
$second_surveillance=$s->format("Y-m-d");
}

if($id>0){

$stmt=$conn->prepare("UPDATE certificates SET
client_id=?,standard=?,number=?,scope=?,accreditation=?,
rdate=?,edate=?,status=?,
first_surveillance=?,second_surveillance=?,
validity_years=?
WHERE id=?");

$stmt->bind_param("isssssssssii",
$client_id,$standard,$number,$scope,$accreditation,
$rdate,$edate,$status,
$first_surveillance,$second_surveillance,
$validity,$id);

}else{

$stmt=$conn->prepare("INSERT INTO certificates
(client_id,standard,number,scope,accreditation,
rdate,edate,status,
first_surveillance,second_surveillance,
validity_years)
VALUES (?,?,?,?,?,?,?,?,?,?,?)");

$stmt->bind_param("isssssssssi",
$client_id,$standard,$number,$scope,$accreditation,
$rdate,$edate,$status,
$first_surveillance,$second_surveillance,
$validity);
}

if(!$stmt->execute()){
die("SQL Error: ".$stmt->error);
}

header("Location: certificates.php");
exit;
?>