<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

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

$success = $error = "";

// Audit logging helper
function audit_log($conn, $userId, $roleId, $action, $details, $module, $deviceInfo) {
    $stmt = $conn->prepare("INSERT INTO audit_log (user_id, role_id, action, details, module, device_info) VALUES (?, ?, ?, ?, ?, ?)");
    if (!$stmt) return false;
    $stmt->bind_param("iissss", $userId, $roleId, $action, $details, $module, $deviceInfo);
    $result = $stmt->execute();
    $stmt->close();
    return $result;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $store_name = trim($_POST['store_name']);
    $store_address = trim($_POST['store_address']);
    $store_contact = trim($_POST['store_contact']);
    $location = trim($_POST['location']);
    $email = trim($_POST['email']);
    $t_pin = trim($_POST['t_pin']);

    if ($store_name && $store_address && $store_contact && $location && $email && $t_pin) {
        $stmt = $conn->prepare("INSERT INTO stores (store_name, store_address, store_contact, location, email, t_pin, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())");
        $stmt->bind_param("ssssss", $store_name, $store_address, $store_contact, $location, $email, $t_pin);

        if ($stmt->execute()) {
            $success = "✅ Store added successfully!";

            // Audit log with JSON details
            $userId = $_SESSION['user_id'];
            $roleId = $_SESSION['role_id'];
            $deviceInfo = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';

            $detailsArr = [
                'store_name' => $store_name,
                'store_address' => $store_address,
                'store_contact' => $store_contact,
                'location' => $location,
                'email' => $email,
                't_pin' => $t_pin
            ];
            $details = json_encode($detailsArr, JSON_UNESCAPED_UNICODE);

            audit_log($conn, $userId, $roleId, "Add Store", $details, "stores", $deviceInfo);
        } else {
            $error = "❌ Failed to add store. Please try again.";
        }
        $stmt->close();
    } else {
        $error = "⚠️ All fields are required.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Store - 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/bg.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 {
            max-width: 600px;
            margin: 120px auto 40px auto;
            padding: 30px 40px;
            background: rgba(255,255,255,0.08);
            border-radius: 20px;
            backdrop-filter: blur(15px);
            box-shadow: 0 8px 32px rgba(0,0,0,0.5);
        }

        h2 {
            text-align: center;
            margin-bottom: 25px;
        }

        form label {
            display: block;
            margin-top: 15px;
            margin-bottom: 5px;
            font-weight: bold;
        }

        form input[type="text"], form input[type="email"] {
            width: 100%;
            padding: 12px;
            border: none;
            border-radius: 10px;
            background: rgba(255,255,255,0.1);
            color: white;
            box-shadow: inset 0 0 5px rgba(255,255,255,0.2);
            outline: none;
        }

        .submit-btn {
            background: #ff6f00;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 25px;
            font-size: 1rem;
            cursor: pointer;
            margin-top: 25px;
            width: 100%;
            transition: background 0.3s ease;
        }

        .submit-btn:hover {
            background: #e65c00;
        }

        .message {
            margin-top: 15px;
            padding: 12px;
            border-radius: 10px;
            text-align: center;
        }

        .message.success {
            background-color: rgba(0,255,0,0.2);
            color: #bfffbf;
        }

        .message.error {
            background-color: rgba(255,0,0,0.2);
            color: #ffb3b3;
        }

        @media (max-width: 600px) {
            .content {
                margin: 60px 20px;
                padding: 20px;
            }
        }
    </style>
</head>
<body>

<div class="overlay"></div>

<div class="content">
    <h2>Add New Store</h2>

    <?php if ($success): ?>
        <div class="message success"><?= $success ?></div>
    <?php elseif ($error): ?>
        <div class="message error"><?= $error ?></div>
    <?php endif; ?>

    <form method="post" action="">
        <label for="store_name">Store Name</label>
        <input type="text" name="store_name" id="store_name" required>

        <label for="store_address">Store Address</label>
        <input type="text" name="store_address" id="store_address" required>

        <label for="store_contact">Store Contact</label>
        <input type="text" name="store_contact" id="store_contact" required>

        <label for="location">Location</label>
        <input type="text" name="location" id="location" required>

        <label for="email">Store Email</label>
        <input type="email" name="email" id="email" required>

        <label for="t_pin">T-PIN</label>
        <input type="text" name="t_pin" id="t_pin" required>

        <button type="submit" class="submit-btn">Add Store</button>
    </form>
</div>

<?php include('../../includes/footer.php'); ?>

</body>
</html>
