39038-vm/admin_truck_owner_edit.php
2026-03-24 03:30:29 +00:00

285 lines
14 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/layout.php'; require_role('admin');
$userId = (int)($_GET['id'] ?? 0);
$isAjax = isset($_GET['ajax']) && $_GET['ajax'] === '1';
if ($userId <= 0) {
if ($isAjax) {
echo json_encode(['success' => false, 'message' => 'Invalid ID']);
exit;
}
header('Location: admin_truck_owners.php');
exit;
}
$errors = [];
$flash = null;
// Fetch Truck Owner Profile
$stmt = db()->prepare("
SELECT u.id, u.email, u.full_name, u.status, u.role,
p.phone, p.address_line, p.country_id, p.city_id,
p.bank_account, p.bank_name, p.bank_branch,
p.id_card_path, p.is_company
FROM users u
LEFT JOIN truck_owner_profiles p ON u.id = p.user_id
WHERE u.id = ? AND u.role = 'truck_owner'
");
$stmt->execute([$userId]);
$owner = $stmt->fetch();
$trucks = db()->prepare("SELECT * FROM trucks WHERE user_id = ?");
$trucks->execute([$userId]);
$ownerTrucks = $trucks->fetchAll();
if (!$owner) {
if ($isAjax) {
echo json_encode(['success' => false, 'message' => 'Owner not found']);
exit;
}
header('Location: admin_truck_owners.php');
exit;
}
$countries = db()->query("SELECT id, name_en, name_ar FROM countries ORDER BY name_en ASC")->fetchAll();
$cities = db()->query("SELECT id, country_id, name_en, name_ar FROM cities ORDER BY name_en ASC")->fetchAll();
if ($_SERVER['REQUEST_METHOD'] === 'POST') { validate_csrf_token();
if (isset($_POST['approve_truck'])) {
$truckId = (int)$_POST['truck_id'];
db()->prepare("UPDATE trucks SET is_approved = 1 WHERE id = ? AND user_id = ?")->execute([$truckId, $userId]);
$flash = 'Truck approved successfully.';
} elseif (isset($_POST['reject_truck'])) {
$truckId = (int)$_POST['truck_id'];
db()->prepare("UPDATE trucks SET is_approved = 0 WHERE id = ? AND user_id = ?")->execute([$truckId, $userId]);
$flash = 'Truck status set to unapproved.';
} else {
$fullName = trim($_POST['full_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$countryId = (int)($_POST['country_id'] ?? 0);
$cityId = (int)($_POST['city_id'] ?? 0);
$addressLine = trim($_POST['address_line'] ?? '');
$status = trim($_POST['status'] ?? '');
$password = $_POST['password'] ?? '';
$bankAccount = trim($_POST['bank_account'] ?? '');
$bankName = trim($_POST['bank_name'] ?? '');
$bankBranch = trim($_POST['bank_branch'] ?? '');
$isCompany = isset($_POST['is_company']) ? 1 : 0;
if ($fullName === '') $errors[] = 'Full name is required.';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required.';
if ($phone === '') $errors[] = 'Phone number is required.';
if (!in_array($status, ['pending', 'active', 'rejected'], true)) $errors[] = 'Invalid status.';
if ($countryId <= 0 || $cityId <= 0) {
$errors[] = 'Please select country and city.';
}
if (!$errors) {
try {
db()->beginTransaction();
$stmtUser = db()->prepare("UPDATE users SET full_name = ?, email = ?, status = ? WHERE id = ? AND role = 'truck_owner'");
$stmtUser->execute([$fullName, $email, $status, $userId]);
if ($password !== '') {
$stmtPass = db()->prepare("UPDATE users SET password = ? WHERE id = ? AND role = 'truck_owner'");
$stmtPass->execute([password_hash($password, PASSWORD_DEFAULT), $userId]);
}
$stmtProfile = db()->prepare("
UPDATE truck_owner_profiles
SET phone = ?, address_line = ?, country_id = ?, city_id = ?,
bank_account = ?, bank_name = ?, bank_branch = ?, is_company = ?
WHERE user_id = ?
");
$stmtProfile->execute([$phone, $addressLine, $countryId, $cityId, $bankAccount, $bankName, $bankBranch, $isCompany, $userId]);
db()->commit();
$flash = 'Truck Owner profile updated successfully.';
} catch (Throwable $e) {
db()->rollBack();
$errors[] = 'Failed to update truck owner profile. Please try again.';
}
}
}
}
// -- OUTPUT START --
if (!$isAjax):
render_header('Edit Truck Owner', 'admin', true);
?>
<div class="row g-0">
<div class="col-md-2 bg-white border-end min-vh-100">
<?php render_admin_sidebar('truck_owners'); ?>
</div>
<div class="col-md-10 p-4">
<div class="page-intro mb-4">
<a href="admin_truck_owners.php" class="text-decoration-none small text-muted mb-2 d-inline-block">&larr; Back to Truck Owners</a>
<h1 class="section-title mb-1">Edit Truck Owner</h1>
</div>
<?php if ($flash): ?>
<div class="alert alert-success" data-auto-dismiss="true"><?= e($flash) ?></div>
<?php endif; ?>
<?php if ($errors): ?>
<div class="alert alert-warning"><?= e(implode('<br>', $errors)) ?></div>
<?php endif; ?>
<div class="panel p-4">
<form method="post" action="admin_truck_owner_edit.php?id=<?= $userId ?>" class="mb-5"> <?= csrf_field() ?>
<h5 class="mb-3">Personal Details</h5>
<div class="row g-3 mb-4">
<div class="col-md-6">
<label class="form-label" for="full_name">Full Name</label>
<input type="text" name="full_name" id="full_name" class="form-control" value="<?= e((string)$owner['full_name']) ?>" required>
</div>
<div class="col-md-6">
<label class="form-label" for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" value="<?= e((string)$owner['email']) ?>" required>
</div>
<div class="col-md-4">
<label class="form-label" for="phone">Phone</label>
<input type="text" name="phone" id="phone" class="form-control" value="<?= e((string)$owner['phone']) ?>" required>
</div>
<div class="col-md-4">
<label class="form-label" for="password">Password <small class="text-muted">(leave blank)</small></label>
<input type="password" name="password" id="password" class="form-control" autocomplete="new-password">
</div>
<div class="col-md-4">
<label class="form-label" for="status">Account Status</label>
<select name="status" id="status" class="form-select" required>
<option value="pending" <?= $owner['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
<option value="active" <?= $owner['status'] === 'active' ? 'selected' : '' ?>>Active</option>
<option value="rejected" <?= $owner['status'] === 'rejected' ? 'selected' : '' ?>>Rejected</option>
</select>
</div>
</div>
<div class="form-check mb-4">
<input class="form-check-input" type="checkbox" name="is_company" id="is_company" value="1" <?= $owner['is_company'] ? 'checked' : '' ?>>
<label class="form-check-label" for="is_company">Register as a company</label>
</div>
<h5 class="mb-3">Location</h5>
<div class="row g-3 mb-4">
<div class="col-md-4">
<label class="form-label" for="country_id">Country</label>
<select name="country_id" id="country_id" class="form-select" onchange="syncCities()" required>
<option value="">Select country</option>
<?php foreach ($countries as $country): ?>
<option value="<?= e((string)$country['id']) ?>" <?= (string)$owner['country_id'] === (string)$country['id'] ? 'selected' : '' ?>>
<?= e($lang === 'ar' && !empty($country['name_ar']) ? $country['name_ar'] : $country['name_en']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-4">
<label class="form-label" for="city_id">City</label>
<select name="city_id" id="city_id" class="form-select" required data-selected="<?= e((string)$owner['city_id']) ?>">
<option value="">Select city</option>
</select>
</div>
<div class="col-md-4">
<label class="form-label" for="address_line">Address Line</label>
<input type="text" name="address_line" id="address_line" class="form-control" value="<?= e((string)$owner['address_line']) ?>" required>
</div>
</div>
<h5 class="mb-3 border-top pt-3">Bank Details</h5>
<div class="row g-3 mb-4">
<div class="col-md-4">
<label class="form-label" for="bank_account">Bank Account / IBAN</label>
<input type="text" name="bank_account" id="bank_account" class="form-control" value="<?= e((string)($owner['bank_account'] ?? '')) ?>">
</div>
<div class="col-md-4">
<label class="form-label" for="bank_name">Bank Name</label>
<input type="text" name="bank_name" id="bank_name" class="form-control" value="<?= e((string)($owner['bank_name'] ?? '')) ?>">
</div>
<div class="col-md-4">
<label class="form-label" for="bank_branch">Bank Branch</label>
<input type="text" name="bank_branch" id="bank_branch" class="form-control" value="<?= e((string)($owner['bank_branch'] ?? '')) ?>">
</div>
</div>
<button type="submit" class="btn btn-primary">Save Changes</button>
</form>
<h5 class="mb-3 border-top pt-3">Registered Trucks</h5>
<table class="table table-bordered">
<thead>
<tr>
<th>Truck Type</th>
<th>Capacity (T)</th>
<th>Plate No</th>
<th>Reg Expiry</th>
<th>Ins Expiry</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($ownerTrucks as $truck): ?>
<?php
$isExpired = (strtotime($truck['registration_expiry_date'] ?? '1900-01-01') < time()) || (strtotime($truck['insurance_expiry_date'] ?? '1900-01-01') < time());
?>
<tr class="<?= $isExpired ? 'table-danger' : '' ?>">
<td><?= e($truck['truck_type']) ?></td>
<td><?= e($truck['load_capacity']) ?></td>
<td><?= e($truck['plate_no']) ?></td>
<td><?= e($truck['registration_expiry_date'] ?? 'N/A') ?></td>
<td><?= e($truck['insurance_expiry_date'] ?? 'N/A') ?></td>
<td>
<?php if ($isExpired): ?>
<span class="badge bg-danger">Expired/Disabled</span>
<?php elseif ($truck['is_approved']): ?>
<span class="badge bg-success">Approved</span>
<?php else: ?>
<span class="badge bg-warning text-dark">Pending</span>
<?php endif; ?>
</td>
<td>
<form method="post" action="admin_truck_owner_edit.php?id=<?= $userId ?>">
<?= csrf_field() ?>
<input type="hidden" name="truck_id" value="<?= e((string)$truck['id']) ?>">
<?php if ($truck['is_approved'] && !$isExpired): ?>
<button type="submit" name="reject_truck" class="btn btn-sm btn-outline-danger">Reject</button>
<?php elseif (!$isExpired): ?>
<button type="submit" name="approve_truck" class="btn btn-sm btn-outline-success">Approve</button>
<?php endif; ?>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
<script>
const allCities = <?= json_encode($cities, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
function syncCities() {
const countryId = document.getElementById('country_id').value;
const citySelect = document.getElementById('city_id');
const selectedValue = citySelect.dataset.selected || '';
citySelect.innerHTML = '<option value="">Select city</option>';
allCities.forEach((city) => {
if (String(city.country_id) !== String(countryId)) return;
const option = document.createElement('option');
option.value = city.id;
option.textContent = '<?= $lang ?>' === 'ar' && city.name_ar ? city.name_ar : (city.name_en || city.name_ar);
if (String(city.id) === String(selectedValue)) option.selected = true;
citySelect.appendChild(option);
});
citySelect.dataset.selected = '';
}
syncCities();
</script>
<?php render_footer(); endif; ?>