<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Properties';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

$form = [
    'id'            => 0,
    'name'          => '',
    'code'          => '',
    'email'         => '',
    'phone'         => '',
    'address'       => '',
    'city'          => '',
    'country_id'    => '',
    'currency_code' => 'USD',
    'is_active'     => '1',
];

$errors = [];
$success = '';
$editing = false;

if (isset($_GET['saved']) && (int)$_GET['saved'] === 1) {
    $success = 'Property saved successfully.';
}
if (isset($_GET['deleted']) && (int)$_GET['deleted'] === 1) {
    $success = 'Property deleted successfully.';
}

$countries = [];
try {
    $stmt = $pdo->query("
        SELECT id, name
        FROM countries
        ORDER BY sequence ASC, name ASC
    ");
    $countries = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
} catch (Throwable $e) {
    $countries = [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_property'])) {
    $form['id']            = (int)($_POST['id'] ?? 0);
    $form['name']          = trim((string)($_POST['name'] ?? ''));
    $form['code']          = strtoupper(trim((string)($_POST['code'] ?? '')));
    $form['email']         = trim((string)($_POST['email'] ?? ''));
    $form['phone']         = trim((string)($_POST['phone'] ?? ''));
    $form['address']       = trim((string)($_POST['address'] ?? ''));
    $form['city']          = trim((string)($_POST['city'] ?? ''));
    $form['country_id']    = trim((string)($_POST['country_id'] ?? ''));
    $form['currency_code'] = strtoupper(trim((string)($_POST['currency_code'] ?? 'USD')));
    $form['is_active']     = (string)((int)($_POST['is_active'] ?? 1));

    $editing = $form['id'] > 0;

    if ($form['name'] === '') {
        $errors[] = 'Property name is required.';
    }
    if ($form['code'] === '') {
        $errors[] = 'Property code is required.';
    }
    if ($form['email'] !== '' && !filter_var($form['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address.';
    }
    if ($form['currency_code'] === '') {
        $errors[] = 'Currency code is required.';
    }

    try {
        $stmt = $pdo->prepare("
            SELECT id
            FROM properties
            WHERE code = :code
              AND id <> :id
            LIMIT 1
        ");
        $stmt->execute([
            ':code' => $form['code'],
            ':id'   => (int)$form['id'],
        ]);
        if ($stmt->fetch(PDO::FETCH_ASSOC)) {
            $errors[] = 'A property with that code already exists.';
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }

    if (!$errors) {
        try {
            if ($editing) {
                $stmt = $pdo->prepare("
                    UPDATE properties
                    SET name = :name,
                        code = :code,
                        email = :email,
                        phone = :phone,
                        address = :address,
                        city = :city,
                        country_id = :country_id,
                        currency_code = :currency_code,
                        is_active = :is_active
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':name'          => $form['name'],
                    ':code'          => $form['code'],
                    ':email'         => $form['email'] !== '' ? $form['email'] : null,
                    ':phone'         => $form['phone'] !== '' ? $form['phone'] : null,
                    ':address'       => $form['address'] !== '' ? $form['address'] : null,
                    ':city'          => $form['city'] !== '' ? $form['city'] : null,
                    ':country_id'    => (int)$form['country_id'] > 0 ? (int)$form['country_id'] : null,
                    ':currency_code' => $form['currency_code'],
                    ':is_active'     => (int)$form['is_active'],
                    ':id'            => (int)$form['id'],
                ]);
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO properties
                    (
                        name,
                        code,
                        email,
                        phone,
                        address,
                        city,
                        country_id,
                        currency_code,
                        is_active
                    )
                    VALUES
                    (
                        :name,
                        :code,
                        :email,
                        :phone,
                        :address,
                        :city,
                        :country_id,
                        :currency_code,
                        :is_active
                    )
                ");
                $stmt->execute([
                    ':name'          => $form['name'],
                    ':code'          => $form['code'],
                    ':email'         => $form['email'] !== '' ? $form['email'] : null,
                    ':phone'         => $form['phone'] !== '' ? $form['phone'] : null,
                    ':address'       => $form['address'] !== '' ? $form['address'] : null,
                    ':city'          => $form['city'] !== '' ? $form['city'] : null,
                    ':country_id'    => (int)$form['country_id'] > 0 ? (int)$form['country_id'] : null,
                    ':currency_code' => $form['currency_code'],
                    ':is_active'     => (int)$form['is_active'],
                ]);
            }

            header('Location: properties.php?saved=1');
            exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (isset($_GET['delete']) && (int)$_GET['delete'] > 0) {
    $deleteId = (int)$_GET['delete'];

    try {
        $stmt = $pdo->prepare("DELETE FROM properties WHERE id = :id");
        $stmt->execute([':id' => $deleteId]);

        header('Location: properties.php?deleted=1');
        exit;
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

if (isset($_GET['edit']) && (int)$_GET['edit'] > 0) {
    $editId = (int)$_GET['edit'];

    try {
        $stmt = $pdo->prepare("SELECT * FROM properties WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $editId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $editing = true;
            $form = [
                'id'            => (int)$row['id'],
                'name'          => (string)$row['name'],
                'code'          => (string)$row['code'],
                'email'         => (string)($row['email'] ?? ''),
                'phone'         => (string)($row['phone'] ?? ''),
                'address'       => (string)($row['address'] ?? ''),
                'city'          => (string)($row['city'] ?? ''),
                'country_id'    => (string)($row['country_id'] ?? ''),
                'currency_code' => (string)($row['currency_code'] ?? 'USD'),
                'is_active'     => (string)(int)($row['is_active'] ?? 1),
            ];
        } else {
            $errors[] = 'Property not found.';
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$search = trim((string)($_GET['q'] ?? ''));

$sql = "
    SELECT
        p.*,
        c.name AS country_name
    FROM properties p
    LEFT JOIN countries c ON c.id = p.country_id
    WHERE 1=1
";
$params = [];

if ($search !== '') {
    $sql .= "
        AND (
            p.name LIKE :search
            OR p.code LIKE :search
            OR p.email LIKE :search
            OR p.city LIKE :search
            OR p.currency_code LIKE :search
            OR c.name LIKE :search
        )
    ";
    $params[':search'] = '%' . $search . '%';
}

$sql .= " ORDER BY p.id DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$properties = $stmt->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-buildings"></i> Masters</div>
            <div class="hero-title mt-2">Properties</div>
            <div class="hero-subtitle mt-2">
                Manage lodges, camps, hotels, and other operational properties in the system.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="properties.php" class="btn btn-outline-light">
                <i class="bi bi-plus-circle me-2"></i>New Property
            </a>
        </div>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success"><?php echo h($success); ?></div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-xl-5">
        <div class="form-section">
            <div class="form-section-title">
                <i class="bi bi-house-add"></i>
                <?php echo $editing ? 'Edit Property' : 'New Property'; ?>
            </div>

            <form method="post" class="row g-3">
                <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>">

                <div class="col-md-8">
                    <label class="form-label">Property Name</label>
                    <input type="text" name="name" class="form-control" value="<?php echo h($form['name']); ?>" required>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Code</label>
                    <input type="text" name="code" class="form-control" value="<?php echo h($form['code']); ?>" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Email</label>
                    <input type="email" name="email" class="form-control" value="<?php echo h($form['email']); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Phone</label>
                    <input type="text" name="phone" class="form-control" value="<?php echo h($form['phone']); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">City</label>
                    <input type="text" name="city" class="form-control" value="<?php echo h($form['city']); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Country</label>
                    <select name="country_id" class="form-select">
                        <option value="">Select country</option>
                        <?php foreach ($countries as $country): ?>
                            <option value="<?php echo (int)$country['id']; ?>" <?php echo (int)$form['country_id'] === (int)$country['id'] ? 'selected' : ''; ?>>
                                <?php echo h($country['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Currency Code</label>
                    <input type="text" name="currency_code" class="form-control" value="<?php echo h($form['currency_code']); ?>" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Active</label>
                    <select name="is_active" class="form-select">
                        <option value="1" <?php echo $form['is_active'] === '1' ? 'selected' : ''; ?>>Yes</option>
                        <option value="0" <?php echo $form['is_active'] === '0' ? 'selected' : ''; ?>>No</option>
                    </select>
                </div>

                <div class="col-12">
                    <label class="form-label">Address</label>
                    <textarea name="address" class="form-control" rows="4"><?php echo h($form['address']); ?></textarea>
                </div>

                <div class="col-12 d-flex gap-2">
                    <button type="submit" name="save_property" value="1" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i><?php echo $editing ? 'Update Property' : 'Save Property'; ?>
                    </button>
                    <a href="properties.php" class="btn btn-light">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card panel-card">
            <div class="card-header">
                <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
                    <h5 class="mb-0">Properties</h5>
                    <form method="get" class="d-flex gap-2">
                        <input type="text" name="q" class="form-control" placeholder="Search properties..." value="<?php echo h($search); ?>">
                        <button class="btn btn-outline-secondary">Search</button>
                    </form>
                </div>
            </div>

            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Property</th>
                                <th>Location</th>
                                <th>Currency</th>
                                <th>Status</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$properties): ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-4">No properties found.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($properties as $row): ?>
                                    <tr>
                                        <td><?php echo (int)$row['id']; ?></td>
                                        <td>
                                            <div class="fw-semibold"><?php echo h($row['name']); ?></div>
                                            <div class="small text-muted"><?php echo h($row['code']); ?></div>
                                        </td>
                                        <td>
                                            <div><?php echo h($row['city'] ?? ''); ?></div>
                                            <div class="small text-muted"><?php echo h($row['country_name'] ?? ''); ?></div>
                                        </td>
                                        <td><?php echo h($row['currency_code'] ?? 'USD'); ?></td>
                                        <td>
                                            <?php if ((int)$row['is_active'] === 1): ?>
                                                <span class="badge text-bg-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge text-bg-secondary">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <div class="d-inline-flex gap-2">
                                                <a href="properties.php?edit=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                                <a href="properties.php?delete=<?php echo (int)$row['id']; ?>"
                                                   class="btn btn-sm btn-outline-danger"
                                                   onclick="return confirm('Delete this property?');">
                                                    Delete
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>