<?php

session_start();


if(!isset($_SESSION['user_id'])){

    header("Location:login.php");
    exit;

}


require_once "config.php";



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



if(!$id){

    header("Location:vendors.php");
    exit;

}





// CHECK VENDOR

$stmt=$pdo->prepare("

SELECT *

FROM vendors

WHERE id=?

");


$stmt->execute([$id]);


$vendor=$stmt->fetch();



if(!$vendor){


    $_SESSION['error']="Vendor not found";

    header("Location:vendors.php");

    exit;

}





// CHECK IF USED IN EXPENSES


$stmt=$pdo->prepare("

SELECT COUNT(*)

FROM expenses

WHERE vendor_id=?

");


$stmt->execute([$id]);


$count=$stmt->fetchColumn();





if($count>0){


    $_SESSION['error']="Cannot delete vendor because expenses are linked to this vendor.";


    header("Location:vendors.php");

    exit;


}






// DELETE


$stmt=$pdo->prepare("

DELETE FROM vendors

WHERE id=?

");


$stmt->execute([$id]);





$_SESSION['success']="Vendor deleted successfully";



header("Location:vendors.php");

exit;


?>