<?php
session_start();
$role_id = $_SESSION['role_id'] ?? null;
$user_id = $_SESSION['user_id'] ?? null;
$store_id = $_SESSION['store_id'] ?? null;

if (!$role_id || !in_array($role_id, [1, 2])) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');
include('../../includes/footer.php');

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid supplier ID.");
}

$id = (int)$_GET['id'];
$stmt = $conn->prepare("SELECT * FROM suppliers WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$supplier = $result->fetch_assoc();
$stmt->close();

if (!$supplier) {
    die("Supplier not found.");
}

$success = $error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $role_id === 1) {
    $supplier_name = trim($_POST['supplier_name']);
    $contact_person = trim($_POST['contact_person']);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);
    $address = trim($_POST['address']);
    $t_pin = trim($_POST['t_pin']);

    if ($supplier_name === '') {
        $error = "Supplier name is required.";
    } else {
        $stmt = $conn->prepare("UPDATE suppliers SET supplier_name=?, contact_person=?, phone=?, email=?, address=?, t_pin=? WHERE id=?");
        $stmt->bind_param("ssssssi", $supplier_name, $contact_person, $phone, $email, $address, $t_pin, $id);

        if ($stmt->execute()) {
            $success = "Supplier updated successfully.";

            // Audit log
            $action_type = 'update';
            $table_name = 'suppliers';
            $record_id = $id;
            $description = 'Updated supplier details';
            $device_info = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';

            $old_values = json_encode([
                'supplier_name' => $supplier['supplier_name'],
                'contact_person' => $supplier['contact_person'],
                'phone' => $supplier['phone'],
                'email' => $supplier['email'],
                'address' => $supplier['address'],
                't_pin' => $supplier['t_pin']
            ], JSON_UNESCAPED_UNICODE);

            $new_values = json_encode([
                'supplier_name' => $supplier_name,
                'contact_person' => $contact_person,
                'phone' => $phone,
                'email' => $email,
                'address' => $address,
                't_pin' => $t_pin
            ], JSON_UNESCAPED_UNICODE);

            $log = $conn->prepare("INSERT INTO audit_logs (action_type, table_name, record_id, user_id, old_values, new_values, description, store_id, device_info, created_at)
                                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $log->bind_param("ssiiissss", $action_type, $table_name, $record_id, $user_id, $old_values, $new_values, $description, $store_id, $device_info);
            $log->execute();
            $log->close();

            // Refresh supplier array for redisplay
            $supplier = [
                'supplier_name' => $supplier_name,
                'contact_person' => $contact_person,
                'phone' => $phone,
                'email' => $email,
                'address' => $address,
                't_pin' => $t_pin
            ];
        } else {
            $error = "Failed to update supplier.";
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Edit Supplier – Digital POS</title>
  <link rel="stylesheet" href="../../css/dashboard.css" />
  <style>
    body, html {
      margin: 0; padding: 0;
      font-family: 'Segoe UI', sans-serif;
      background: url('../../images/profile.jpg') no-repeat center center fixed;
      background-size: cover;
      color: white;
      min-height: 100vh;
    }
    .overlay {
      position: fixed; top: 0; left: 0;
      width: 100%; height: 100%;
      background: rgba(0,0,0,0.6);
      z-index: -1;
    }
    .content {
      margin: 100px auto 40px auto;
      max-width: 600px;
      padding: 30px 40px;
      backdrop-filter: blur(15px);
      background: rgba(255, 255, 255, 0.08);
      border-radius: 20px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
    }
    h2 {
      text-align: center;
      margin-bottom: 25px;
      font-size: 1.6rem;
    }
    form label {
      display: block;
      margin-top: 15px;
      font-weight: bold;
    }
    form input, form textarea {
      width: 100%;
      padding: 12px;
      margin-top: 6px;
      border: none;
      border-radius: 10px;
      background: rgba(255,255,255,0.1);
      color: white;
      font-size: 14px;
    }
    form button {
      background: #ff6f00;
      color: white;
      font-weight: bold;
      border: none;
      padding: 12px 20px;
      border-radius: 25px;
      cursor: pointer;
      margin-top: 20px;
      width: 100%;
    }
    form button:hover {
      background: #e65c00;
    }
    form button[disabled] {
      opacity: 0.6;
      cursor: not-allowed;
    }
    #toast {
      position: fixed;
      top: 20px;
      right: 20px;
      min-width: 240px;
      padding: 12px 20px;
      border-radius: 8px;
      font-weight: bold;
      box-shadow: 0 4px 8px rgba(0,0,0,0.4);
      display: none;
      z-index: 999;
      color: white;
    }
    #toast.success { background: #4caf50; }
    #toast.error { background: #f44336; }
  </style>
</head>
<body>
<div class="overlay"></div>
<div id="toast"></div>

<div class="content">
  <h2>Edit Supplier</h2>
  <form method="POST">
    <label>Supplier Name *</label>
    <input type="text" name="supplier_name" value="<?= htmlspecialchars($supplier['supplier_name']) ?>" required <?= $role_id != 1 ? 'readonly' : '' ?>>

    <label>Contact Person</label>
    <input type="text" name="contact_person" value="<?= htmlspecialchars($supplier['contact_person']) ?>" <?= $role_id != 1 ? 'readonly' : '' ?>>

    <label>Phone</label>
    <input type="text" name="phone" value="<?= htmlspecialchars($supplier['phone']) ?>" <?= $role_id != 1 ? 'readonly' : '' ?>>

    <label>Email</label>
    <input type="email" name="email" value="<?= htmlspecialchars($supplier['email']) ?>" <?= $role_id != 1 ? 'readonly' : '' ?>>

    <label>Address</label>
    <textarea name="address" rows="3" <?= $role_id != 1 ? 'readonly' : '' ?>><?= htmlspecialchars($supplier['address']) ?></textarea>

    <label>Tax PIN (TPIN)</label>
    <input type="text" name="t_pin" value="<?= htmlspecialchars($supplier['t_pin']) ?>" <?= $role_id != 1 ? 'readonly' : '' ?>>

    <button type="submit" <?= $role_id != 1 ? 'disabled title="Managers cannot edit suppliers"' : '' ?>>Update Supplier</button>
  </form>
</div>

<script>
  function showToast(msg, type='success') {
    const t = document.getElementById('toast');
    t.textContent = msg;
    t.className = type;
    t.style.display = 'block';
    setTimeout(() => t.style.display = 'none', 3500);
  }

  <?php if ($success): ?> showToast("<?= addslashes($success) ?>", 'success'); <?php endif; ?>
  <?php if ($error): ?> showToast("<?= addslashes($error) ?>", 'error'); <?php endif; ?>
</script>
</body>
</html>
