<?php
ob_start();

include_once '../includes/constants.php';
include_once '../includes/functions.php';
include_once '../includes/session.php';

$partners = new partners();
$partners->connection($host, $user, $pass, $db);

$mysqli = $partners->mysqli;

// Sanitize GET parameters
$mode = isset($_GET['mode']) ? $_GET['mode'] : '';
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Sanitize POST input
$language = isset($_POST['language']) ? trim($_POST['language']) : '';
$status = isset($_POST['status']) ? trim($_POST['status']) : '';

// Validation for non-delete modes
if ($mode !== "delete" && $language === '') {
    header("Location: index.php?Act=languages&mode=$mode&id=$id&msg=Blank value");
    exit;
}

// Add new language
if ($mode === "add") {
    $stmt = $mysqli->prepare("INSERT INTO partners_languages (languages_name, languages_status) VALUES (?, ?)");
    if ($stmt) {
        $stmt->bind_param("ss", $language, $status);
        $stmt->execute();
        $stmt->close();
        header("Location: index.php?Act=languages&mode=add&id=$id&msg=Language Added Successfully");
    } else {
        die("Database Error: " . $mysqli->error);
    }
    exit;
}

// Edit existing language
if ($mode === "edit" && $id > 0) {
    $stmt = $mysqli->prepare("UPDATE partners_languages SET languages_name = ?, languages_status = ? WHERE languages_id = ?");
    if ($stmt) {
        $stmt->bind_param("ssi", $language, $status, $id);
        $stmt->execute();
        $stmt->close();
        header("Location: index.php?Act=languages&mode=add&msg=Language Updated Successfully");
    } else {
        die("Database Error: " . $mysqli->error);
    }
    exit;
}

// Delete language
if ($mode === "delete" && $id > 0) {
    $stmt = $mysqli->prepare("DELETE FROM partners_languages WHERE languages_id = ?");
    if ($stmt) {
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();
        header("Location: index.php?Act=languages&mode=add&msg=Language Deleted Successfully");
    } else {
        die("Database Error: " . $mysqli->error);
    }
    exit;
}

// If mode is unknown or ID is invalid
header("Location: index.php?Act=languages&mode=add&msg=Invalid operation");
exit;
?>
