<?php
include("../includes/db_connection.php");
include("../includes/auth.php");
include("partials/header.php");

$id = $_GET['id'] ?? '';

$client_id="";
$standard="";
$number="";
$scope="";
$accreditation="";
$rdate="";
$edate="";
$status="Active";
$first_surveillance="";
$second_surveillance="";
$reason="";

if($id){
    $stmt = $conn->prepare("SELECT * FROM certificates WHERE id=?");
    $stmt->bind_param("i",$id);
    $stmt->execute();
    $data = $stmt->get_result()->fetch_assoc();
    if($data){
        extract($data);
    }
}
?>

<div class="container py-4">
<div class="card shadow">
<div class="card-header bg-dark text-white">
<?= $id ? "Edit Certificate" : "Add Certificate" ?>
</div>

<div class="card-body">
<form method="POST" action="certificate_save.php">

<input type="hidden" name="id" value="<?= $id ?>">

<div class="row g-3">

<div class="col-md-6">
<label>Client *</label>
<select name="client_id" class="form-select" required>
<option value="">Select Client</option>
<?php
$clients=$conn->query("SELECT id,name FROM clients ORDER BY name ASC");
while($c=$clients->fetch_assoc()):
?>
<option value="<?= $c['id'] ?>" <?= ($client_id==$c['id'])?'selected':'' ?>>
<?= $c['name'] ?>
</option>
<?php endwhile; ?>
</select>
</div>

<div class="col-md-6">
<label>Certificate Number *</label>
<input type="text" name="number" id="certificate_number"
class="form-control"
value="<?= $number ?>" required>
<small id="cert_feedback"></small>
</div>

<div class="col-md-6">
<label>Standard *</label>
<select name="standard" class="form-select" required>
<option value="">Select Standard</option>
<?php
$stds=$conn->query("SELECT name FROM standards WHERE status='Active' ORDER BY name ASC");
while($s=$stds->fetch_assoc()):
?>
<option value="<?= $s['name'] ?>"
<?= ($standard==$s['name'])?'selected':'' ?>>
<?= $s['name'] ?>
</option>
<?php endwhile; ?>
</select>
</div>

<div class="col-md-6">
<label>Accreditation</label>
<input type="text" name="accreditation" class="form-control" value="<?= $accreditation 
?>">
</div>

<div class="col-md-6">
<label>Registration Date *</label>
<input type="date" name="rdate" id="rdate" class="form-control" value="<?= $rdate ?>" 
required>
</div>

<div class="col-md-6">
<label>Validity *</label>
<select name="validity_years" id="validity_years" class="form-select" required>
<option value="1" <?= ($validity_years==1)?'selected':'' ?>>1 Year</option>
<option value="3" <?= ($validity_years==3)?'selected':'' ?>>3 Years</option>
</select>
</div>

<div class="col-md-6">
<label>Expiry Date</label>
<input type="date" name="edate" id="edate" class="form-control" value="<?= $edate ?>" 
readonly>
</div>

<div class="col-md-6">
<label>1st Surveillance</label>
<input type="date" name="first_surveillance" class="form-control" value="<?= 
$first_surveillance ?>">
</div>

<div class="col-md-6">
<label>2nd Surveillance</label>
<input type="date" name="second_surveillance" class="form-control" value="<?= 
$second_surveillance ?>">
</div>

<div class="col-md-6">
<label>Status</label>
<select name="status" class="form-select">
<option value="Active" <?= $status=="Active"?'selected':'' ?>>Active</option>
<option value="Suspended" <?= $status=="Suspended"?'selected':'' ?>>Suspended</option>
<option value="Withdrawn" <?= $status=="Withdrawn"?'selected':'' ?>>Withdrawn</option>
</select>
</div>

<div class="col-12">
<label>Scope</label>
<textarea name="scope" class="form-control"><?= $scope ?></textarea>
</div>

<div class="col-12">
<label>Reason (If Suspended / Withdrawn)</label>
<textarea name="reason" class="form-control"><?= $reason ?></textarea>
</div>

<div class="col-12 mt-3">
<button class="btn btn-success">
<?= $id ? "Update Certificate" : "Save Certificate" ?>
</button>
<a href="certificates.php" class="btn btn-secondary">Back</a>
</div>

</div>
</form>
</div>
</div>
</div>
<script>
document.getElementById("certificate_number").addEventListener("blur", function(){

let number = this.value;
let id = "<?= $id ?>";

if(number === '') return;

fetch("check_certificate_number.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: "number=" + encodeURIComponent(number) + "&id=" + id
})
.then(response => response.text())
.then(data => {

let feedback = document.getElementById("cert_feedback");

if(data === "exists"){
feedback.innerHTML = "<span class='text-danger'>Certificate number already exists</span>";
}else if(data === "available"){
feedback.innerHTML = "<span class='text-success'>Certificate number available</span>";
}

});

});
</script>
<script>

function calculateExpiry(){

let rdate = document.getElementById("rdate").value;
let validity = document.getElementById("validity_years").value;

if(!rdate || !validity) return;

let d = new Date(rdate);

// Add years
d.setFullYear(d.getFullYear() + parseInt(validity));

// Minus 1 day
d.setDate(d.getDate() - 1);

let m = String(d.getMonth()+1).padStart(2,'0');
let day = String(d.getDate()).padStart(2,'0');

document.getElementById("edate").value =
d.getFullYear()+"-"+m+"-"+day;
}

document.getElementById("rdate").addEventListener("change", calculateExpiry);
document.getElementById("validity_years").addEventListener("change", calculateExpiry);

</script>
<!--
<script>
document.getElementById("rdate").addEventListener("change", function(){
let d = new Date(this.value);
d.setFullYear(d.getFullYear()+3);
d.setDate(d.getDate()-1);

let m = String(d.getMonth()+1).padStart(2,'0');
let day = String(d.getDate()).padStart(2,'0');

document.getElementById("edate").value =
d.getFullYear()+"-"+m+"-"+day;
});
</script>
-->
<?php include("partials/footer.php"); ?>