<?php 
    session_start();
    if(!$_SESSION['id']){
      header('location:index.php');
    }
      require_once '../system/conn.php';
?>
<?php 

if(isset($_POST["submit"])) {
    $e_id = $_GET['id'];
    extract($_POST);

    // Check if we are editing
    if(isset($_POST['edit'])) {
        $select = $conn->prepare("SELECT `photo` FROM `candidate_details` WHERE `id` = ?");
        $select->execute([$e_id]);
        $data = $select->fetch();

        if ($data && !empty($data['photo'])) {
            $old_image = "../assets/images/candidates/" . $data['photo'];
            if (file_exists($old_image)) {
                unlink($old_image);
            }
        }
    }

    // Handling File Upload
    $temp_file = $_FILES['img']['tmp_name'];
    $file_name = $_FILES['img']['name'];
    $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $allowed_extensions = array('jpg', 'jpeg', 'png', 'webp');

    if (!in_array($extension, $allowed_extensions)) {
        echo "<script>alert('Kindly upload a valid image file format (JPG, PNG, WEBP).');</script>";
    } else {
        // Generate a new unique file name
        $new_file_name = rand(1000, 9999) . '-' . date('YmdHis') . '.webp';
        $upload_path = "../assets/images/candidates/" . $new_file_name;

        // Convert image to WebP
        switch ($extension) {
            case 'jpg':
            case 'jpeg':
                $image = imagecreatefromjpeg($temp_file);
                break;
            case 'png':
                $image = imagecreatefrompng($temp_file);
                break;
            case 'webp':
                move_uploaded_file($temp_file, $upload_path); // No conversion needed
                $image = false;
                break;
            default:
                echo "<script>alert('Unsupported image format.');</script>";
                exit;
        }

        if ($image) {
            imagewebp($image, $upload_path, 80); // Convert and save WebP image
            imagedestroy($image);
        }

        // Update database
        $query = "UPDATE `candidate_details` SET `photo` = ? WHERE `id` = ?";
        $statement = $conn->prepare($query)->execute([$new_file_name, $e_id]);

        if ($statement) {
            echo "<script>alert('Candidate image updated successfully.');</script>";
            echo "<script>window.location.href = 'all-candidates.php';</script>";
        } else {
            echo "<script>alert('Something went wrong!');</script>";
        }
    }
}
?>

<!doctype html>
<html lang="en" class="semi-dark">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- loader-->
	<link href="assets/css/pace.min.css" rel="stylesheet" />
	<script src="assets/js/pace.min.js"></script>
    <!--plugins-->
    <link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
    <link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
    <link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
    <!-- CSS Files -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/icons.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
    <!--Theme Styles-->
    <link href="assets/css/dark-theme.css" rel="stylesheet" />
    <link href="assets/css/semi-dark.css" rel="stylesheet" />
    <link href="assets/css/header-colors.css" rel="stylesheet" />
    <title>Edit Candidate Image</title>
  </head>
  <body>
    
  <!--start wrapper-->
  <div class="wrapper">
    <?php include'system/header.php'?>
    <!--end top header-->

        <!-- start page content wrapper-->
        <div class="page-content-wrapper">
          <!-- start page content-->
         <div class="page-content">

            <!--start breadcrumb-->
            <div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
              <div class="breadcrumb-title pe-3">Edit Candidate Image</div>
            </div>
            <!--end breadcrumb-->

            <div class="row">
              <div class="col-xl-12 mx-auto">
                
                <div class="card">
                  <div class="card-body">
                    <div class="p-4 border rounded">
                        
                      <form class="row g-3 needs-validation" novalidate method="post" enctype="multipart/form-data" action="">
                        <h6 class="mb-0 text-uppercase">Edit Candidate Image :</h6>
                        <hr/>
                        <?php
                          $sth = $conn->prepare(" SELECT * FROM `candidate_details` where `id`=? ");
                          $sth->execute([$_GET['id']]);
                          $user = $sth->fetch(PDO::FETCH_ASSOC);
                        
                        ?>
                        <div class="col-md-4">
                          <div class="input-field">
                            <input type="file" name="img" class="form-control mb-4" id="imgInput" accept="image/*" required>
                            <img id="previewImg" src="../assets/images/candidates/<?php echo $user['photo'] ? $user['photo'] : 'dummy-user.webp'; ?>" class="img-thumbnail" alt="No image" style="width:150px">
                          </div>
                        </div>
                        <div class="col-12">
                          <button class="btn btn-primary" type="submit" name="submit" value="submit" >Save Changes</button>
                        </div>
                      </form>
                    </div>
                  </div>
                </div>
                
                
              </div>
            </div>
            <!--end row-->


          </div>
          <!-- end page content-->
         </div>
<?php include 'system/footer.php'?>
<script>
document.getElementById('imgInput').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('previewImg').src = e.target.result;
        };
        reader.readAsDataURL(file);
    }
});
</script>