<?php
include_once '../config/connect.php';
include_once '../config/provider_image.php';
include_once __DIR__ . '/../../../../vendor/autoload.php';

if (isset($_POST['add_provider'])) {
    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);
    
    $provider_codex = $purifier->purify($_POST['provider_code']);
    $provider_namex = $purifier->purify($_POST['provider_name']);
    $provider_typex = $purifier->purify($_POST['provider_type']);
    $provider_statusx = $purifier->purify($_POST['provider_status']);
    $providerImageUpload = provider_upload_image();
    
    $provider_code = mysqli_real_escape_string($call, $provider_codex);
    $provider_name = mysqli_real_escape_string($call, $provider_namex);
    $provider_type = mysqli_real_escape_string($call, $provider_typex);
    $provider_status = mysqli_real_escape_string($call, $provider_statusx);

    if (!$providerImageUpload['ok'] || (string)$providerImageUpload['path'] === '') {
        header('Location: ../index?page=Provider&msg=76');
        exit();
    }

    $provider_image = mysqli_real_escape_string($call, (string)$providerImageUpload['path']);

    $checkQuery = "SELECT * FROM tb_provider WHERE provider_code = '$provider_code'";
    $checkResult = mysqli_query($call, $checkQuery);

    if (mysqli_num_rows($checkResult) > 0) {
        header('Location: ../index?page=Provider&msg=32');
        exit();
    }

    $query = "INSERT INTO tb_provider (provider_code, provider_name, provider_type, provider_status, provider_image) 
              VALUES ('$provider_code', '$provider_name', '$provider_type', '$provider_status', '$provider_image')";

    if (mysqli_query($call, $query)) {
        header('Location: ../index?page=Provider&msg=34');
        exit();
    } else {
        header('Location: ../index?page=Provider&msg=33');
        exit();
    }
}
?>
