<?php
ob_start();

//=============================================================================//
//  Last Modified : Modernized by ChatGPT on 2025-08-20                        //
//  Script Name   : admin_currency.php                                        //
//=============================================================================//

require_once '../includes/session.php';
require_once '../includes/constants.php';
require_once '../includes/functions.php';
require_once '../includes/allstripslashes.php';

// Create DB connection
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
    die("Database connection failed: " . $mysqli->connect_error);
}

// Retrieve form variables
$currency_caption  = trim(stripslashes($_POST['currency_caption'] ?? ''));
$currency_relation = trim(stripslashes($_POST['currency_relation'] ?? ''));
$mode              = trim(stripslashes($_GET['mode'] ?? ''));
$id                = intval(trim(stripslashes($_GET['id'] ?? 0)));

// Get symbol from predefined array if available
$currency_symbol = $currArray[$currency_caption] ?? '';

// Delete currency
if ($mode === "delete") {
    $caption = $mysqli->real_escape_string($_GET['caption'] ?? '');
    $stmt = $mysqli->prepare("DELETE FROM partners_currency WHERE currency_caption = ?");
    $stmt->bind_param("s", $caption);
    $stmt->execute();
    $stmt->close();
    header("Location: index.php?Act=currency&mode=add");
    exit;
}

// URL for redirect if validation fails
$url = "index.php?Act=currency&id=$id&mode=$mode&currency_caption=$currency_caption&currency_symbol=$currency_symbol&currency_relation=$currency_relation";

// Validation
$err = (empty($currency_caption) ? "1" : "0") . "." . (empty($currency_relation) ? "1" : "0");
if ($err !== "0.0") {
    header("Location: $url&msg=1");
    exit;
}

if (!is_numeric($currency_relation)) {
    header("Location: $url&msg=8");
    exit;
}

$currency_caption = addslashes($currency_caption);
$currency_symbol = addslashes($currency_symbol);
$today = date("Y-m-d");

// Check if currency exists
$stmt = $mysqli->prepare("SELECT * FROM partners_currency WHERE currency_code = ?");
$stmt->bind_param("s", $currency_caption);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $stmt->close();
    $stmt_relation = $mysqli->prepare("INSERT INTO partners_currency_relation (relation_currency_code, relation_value, relation_date) VALUES (?, ?, ?)");
    $stmt_relation->bind_param("sds", $currency_caption, $currency_relation, $today);
    $stmt_relation->execute();
    $stmt_relation->close();
    $msg = 4;
} else {
    $msg = 12;
}

header("Location: index.php?Act=currency&msg=$msg");
exit;
?>
