<?php
session_start();
include '../../assets/constant/config.php';

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// connect author at mdkhairnar92@gmail.com 
    if (isset($_POST['submit'])) {
         if (!isset($_SESSION['token'])|| (!isset($_POST['token'])))
             {
                exit('token is not set');
             }

                if($_SESSION['token']==$_POST['token'])
                 {
                   echo "OK";

                   
        if(isset($_SESSION['id'])){
        $user_id = $_SESSION['id'];
    } else {
        // Handle the case where user_id is not set in the session
        // You may want to redirect the user or display an error message
        exit("User ID not set in session.");
    }

      $name=$_POST['name'];
      $notes=$_POST['notes'];
        $stmt = $conn->prepare("INSERT INTO `branch`(`user_id`,`branch_name`,`notes`) VALUES (?,?,?)");
         $stmt->bindParam(1, $user_id);
        $stmt->bindParam(2, htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8'));
        $stmt->bindParam(3, htmlspecialchars($_POST['notes'], ENT_QUOTES, 'UTF-8'));
       

        $stmt->execute();

        $_SESSION['success'] = "success";

        header("location:../manage_branch.php");
    }

}



//update branch
    if (isset($_POST['update'])) {
    // Prepare the SQL statement
    $stmt = $conn->prepare("UPDATE `branch` SET `branch_name`=?, `notes`=? WHERE b_id= ?");
    
    // Bind parameters
    $stmt->bindParam(1, $_POST['name'], PDO::PARAM_STR);
    $stmt->bindParam(2, $_POST['notes'], PDO::PARAM_STR);
    $stmt->bindParam(3, $_POST['id'], PDO::PARAM_INT);

    // Execute the statement
    $stmt->execute();

    // Set session variable
    $_SESSION['update'] = "update";

    // Redirect to manage_branch.php
    header("location:../manage_branch.php");
}
    // connect author at mdkhairnar92@gmail.com 

    if (isset($_POST['del_id'])) {

        $stmt = $conn->prepare("UPDATE `branch` SET delete_status='1' where b_id=? ");

        $stmt->execute([htmlspecialchars($_POST['del_id'], ENT_QUOTES, 'UTF-8')]);

        $_SESSION['delete'] = "delete";

        header("location:../manage_branch.php");
    }
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
