<?php
session_start();

require_once '../Config/Database.php';
require_once '../Model/Supplier.php';
$supplier = new Supplier();

$suppliers = $supplier->read_all_suppliers();

if(isset($_GET['all_suppliers'])){
    echo json_encode(
        array("data"=>$suppliers)
    ); 
}

if(isset($_POST['add_supplier'])){
    $supplier_company = $_POST['supplier_company'];
    $supplier_name = $_POST['supplier_name'];
    $supplier_phone = $_POST['supplier_phone'];
    $supplier_email = $_POST['supplier_email'];
    $supplier_digital_address = $_POST['supplier_digital_address'];
    $data = array(
        "supplier_company"=>$supplier_company,
        "supplier_name"=>$supplier_name,
        "supplier_phone"=>$supplier_phone,
        "supplier_email"=>$supplier_email,
        "supplier_digital_address"=>$supplier_digital_address,
    );
    $success = $supplier->add_supplier($data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

if(isset($_POST['update_supplier'])){
    $supplier_id = $_POST['supplier_id'];
    $supplier_company = $_POST['supplier_company'];
    $supplier_name = $_POST['supplier_name'];
    $supplier_phone = $_POST['supplier_phone'];
    $supplier_email = $_POST['supplier_email'];
    $supplier_digital_address = $_POST['supplier_digital_address'];
    $data = array(
        "supplier_company"=>$supplier_company,
        "supplier_name"=>$supplier_name,
        "supplier_phone"=>$supplier_phone,
        "supplier_email"=>$supplier_email,
        "supplier_digital_address"=>$supplier_digital_address,
    );
    $key = array(
        "supplier_id"=>$supplier_id
    );
    $success = $supplier->update_supplier($key,$data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}


if(isset($_POST['remove_supplier'])){
    $supplier_id = $_POST['supplier_id'];
    $data = $supplier->remove_supplier($supplier_id);
    if(!$data){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}