<?php
session_start();
if(empty($_SESSION['branch']) || $_SESSION['branch'] == ''){
    header("Location: index.php");
    die();
}
require_once 'system/conn.php';

// 1. Validate Inputs
if(!isset($_GET['e-id']) || !isset($_GET['branch'])){
    echo "<script>alert('Invalid Request'); window.location.href='all-employees.php';</script>";
    die();
}

$e_id   = $_GET['e-id'];
$branch = $_GET['branch'];
$doj    = isset($_GET['doj']) ? $_GET['doj'] : ''; // Join Date
$dol    = date('Y-m-d'); // Date of Leaving (Today)
$status = 1; // Status for left_employee table (1 = Active in Left list)

try {
    // 2. Begin Transaction (Ensures both queries work, or neither does)
    $conn->beginTransaction();

    // STEP A: Mark as Inactive in Main Table
    $stmt1 = $conn->prepare("UPDATE emp_details SET status = 0 WHERE e_id = ? AND branch = ?");
    $stmt1->execute([$e_id, $branch]);

    // STEP B: Add to Left Employees Table
    // Note: Assuming 'entry_date' refers to their original DOJ
    $stmt2 = $conn->prepare("INSERT INTO left_employee (emp_id, d_o_l, entry_date, branch, status) VALUES (?, ?, ?, ?, ?)");
    $stmt2->execute([$e_id, $dol, $doj, $branch, $status]);

    // 3. Commit Changes
    $conn->commit();

    echo "<script>
            alert('Employee Marked as Left Successfully');
            window.location.href='all-employees.php';
          </script>";

} catch (Exception $e) {
    // If error, undo everything
    $conn->rollBack();
    echo "Error: " . $e->getMessage();
}
?>