<?php
/**
 * Edit Buyer
 * LandSales Pro - Edit buyer details
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];
$buyerId = intval($_GET['id'] ?? 0);
$errors = [];

// File upload settings
$uploadDir = __DIR__ . '/../../uploads/buyers/';
$allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$allowedDocTypes = ['application/pdf'];
$maxFileSize = 5 * 1024 * 1024; // 5MB

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

/**
 * Handle file upload
 */
function handleFileUpload($file, $uploadDir, $allowedTypes, $maxSize, $prefix) {
    if ($file['error'] === UPLOAD_ERR_NO_FILE) {
        return ['success' => true, 'filename' => null];
    }

    if ($file['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'error' => 'File upload error'];
    }

    if ($file['size'] > $maxSize) {
        return ['success' => false, 'error' => 'File too large (max 5MB)'];
    }

    if (!in_array($file['type'], $allowedTypes)) {
        return ['success' => false, 'error' => 'Invalid file type'];
    }

    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = $prefix . '_' . time() . '_' . bin2hex(random_bytes(8)) . '.' . $extension;
    $destination = $uploadDir . $filename;

    if (move_uploaded_file($file['tmp_name'], $destination)) {
        return ['success' => true, 'filename' => $filename];
    }

    return ['success' => false, 'error' => 'Failed to save file'];
}

/**
 * Delete old file
 */
function deleteOldFile($filename, $uploadDir) {
    if ($filename && file_exists($uploadDir . $filename)) {
        unlink($uploadDir . $filename);
    }
}

if (!$buyerId) {
    header('Location: index.php');
    exit;
}

// Get buyer
$buyer = db_fetch_one("SELECT * FROM buyers WHERE id = ? AND user_id = ?", 'ii', [$buyerId, $userId]);

if (!$buyer) {
    setFlashMessage('error', 'Buyer not found');
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullName = trim($_POST['full_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $idType = $_POST['id_type'] ?? '';
    $idNumber = trim($_POST['id_number'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $notes = trim($_POST['notes'] ?? '');

    // Validation
    if (empty($fullName)) $errors[] = "Full name is required";
    if (empty($phone)) $errors[] = "Phone number is required";
    if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format";

    // Check for duplicate phone (excluding current)
    if (empty($errors)) {
        $existing = db_fetch_one("SELECT id FROM buyers WHERE user_id = ? AND phone = ? AND id != ?", 'isi', [$userId, $phone, $buyerId]);
        if ($existing) {
            $errors[] = "Another buyer with this phone number already exists";
        }
    }

    // Handle file uploads
    $photoFilename = $buyer['photo'];
    $idImageFilename = $buyer['id_image'];
    $idDocumentFilename = $buyer['id_document'];

    // Handle delete requests
    if (isset($_POST['delete_photo']) && $buyer['photo']) {
        deleteOldFile($buyer['photo'], $uploadDir);
        $photoFilename = null;
    }
    if (isset($_POST['delete_id_image']) && $buyer['id_image']) {
        deleteOldFile($buyer['id_image'], $uploadDir);
        $idImageFilename = null;
    }
    if (isset($_POST['delete_id_document']) && $buyer['id_document']) {
        deleteOldFile($buyer['id_document'], $uploadDir);
        $idDocumentFilename = null;
    }

    // Handle new uploads
    if (empty($errors) && !empty($_FILES['photo']['name'])) {
        $result = handleFileUpload($_FILES['photo'], $uploadDir, $allowedImageTypes, $maxFileSize, 'photo');
        if (!$result['success']) {
            $errors[] = "Photo: " . $result['error'];
        } else {
            deleteOldFile($buyer['photo'], $uploadDir);
            $photoFilename = $result['filename'];
        }
    }

    if (empty($errors) && !empty($_FILES['id_image']['name'])) {
        $result = handleFileUpload($_FILES['id_image'], $uploadDir, $allowedImageTypes, $maxFileSize, 'id_img');
        if (!$result['success']) {
            $errors[] = "ID Image: " . $result['error'];
        } else {
            deleteOldFile($buyer['id_image'], $uploadDir);
            $idImageFilename = $result['filename'];
        }
    }

    if (empty($errors) && !empty($_FILES['id_document']['name'])) {
        $result = handleFileUpload($_FILES['id_document'], $uploadDir, $allowedDocTypes, $maxFileSize, 'id_doc');
        if (!$result['success']) {
            $errors[] = "ID Document: " . $result['error'];
        } else {
            deleteOldFile($buyer['id_document'], $uploadDir);
            $idDocumentFilename = $result['filename'];
        }
    }

    if (empty($errors)) {
        $sql = "UPDATE buyers SET full_name = ?, phone = ?, email = ?, id_type = ?, id_number = ?, address = ?, notes = ?, photo = ?, id_image = ?, id_document = ? WHERE id = ? AND user_id = ?";

        if (db_execute($sql, 'ssssssssssii', [$fullName, $phone, $email ?: null, $idType ?: null, $idNumber ?: null, $address ?: null, $notes ?: null, $photoFilename, $idImageFilename, $idDocumentFilename, $buyerId, $userId])) {
            logActivity('buyer_updated', "Updated buyer: {$fullName}");
            setFlashMessage('success', 'Buyer updated successfully!');
            header('Location: view.php?id=' . $buyerId);
            exit;
        } else {
            $errors[] = "Failed to update buyer. Please try again.";
        }
    }
} else {
    // Pre-fill form
    $_POST = $buyer;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Buyer - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Edit Buyer</h1>
            <div class="header-actions">
                <a href="view.php?id=<?php echo $buyerId; ?>" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="form-container">
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <form method="POST" enctype="multipart/form-data" class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-user-edit"></i> Buyer Information</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label for="full_name">Full Name *</label>
                            <input type="text" name="full_name" id="full_name" class="form-control"
                                   value="<?php echo htmlspecialchars($_POST['full_name'] ?? ''); ?>"
                                   placeholder="e.g., John Mwamba" required>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="phone">Phone Number *</label>
                                <input type="tel" name="phone" id="phone" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>"
                                       placeholder="e.g., 0712345678" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="email" name="email" id="email" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>"
                                       placeholder="e.g., john@example.com">
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="id_type">ID Type</label>
                                <select name="id_type" id="id_type" class="form-control">
                                    <option value="">-- Select --</option>
                                    <option value="nida" <?php echo ($_POST['id_type'] ?? '') === 'nida' ? 'selected' : ''; ?>>NIDA</option>
                                    <option value="passport" <?php echo ($_POST['id_type'] ?? '') === 'passport' ? 'selected' : ''; ?>>Passport</option>
                                    <option value="driving_license" <?php echo ($_POST['id_type'] ?? '') === 'driving_license' ? 'selected' : ''; ?>>Driving License</option>
                                    <option value="voter_id" <?php echo ($_POST['id_type'] ?? '') === 'voter_id' ? 'selected' : ''; ?>>Voter ID</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="id_number">ID Number</label>
                                <input type="text" name="id_number" id="id_number" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['id_number'] ?? ''); ?>"
                                       placeholder="e.g., 19900101-XXXXX-XXXXX-XX">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="address">Address</label>
                            <textarea name="address" id="address" class="form-control" rows="2"
                                      placeholder="Physical address..."><?php echo htmlspecialchars($_POST['address'] ?? ''); ?></textarea>
                        </div>

                        <div class="form-group">
                            <label for="notes">Notes</label>
                            <textarea name="notes" id="notes" class="form-control" rows="2"
                                      placeholder="Additional notes..."><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <!-- Documents Section -->
                    <div class="card-header" style="border-top: 1px solid #f1f5f9;">
                        <h3><i class="fas fa-file-image"></i> Documents & Photos</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-row">
                            <div class="form-group">
                                <label for="photo">Buyer Photo</label>
                                <?php if ($buyer['photo']): ?>
                                <div class="current-file">
                                    <img src="<?php echo SITE_URL; ?>/uploads/buyers/<?php echo htmlspecialchars($buyer['photo']); ?>" alt="Current photo">
                                    <label class="delete-checkbox">
                                        <input type="checkbox" name="delete_photo" value="1"> Remove
                                    </label>
                                </div>
                                <?php endif; ?>
                                <div class="file-upload-wrapper">
                                    <input type="file" name="photo" id="photo" class="file-input" accept="image/*" onchange="previewImage(this, 'photo-preview')">
                                    <label for="photo" class="file-label">
                                        <i class="fas fa-camera"></i>
                                        <span><?php echo $buyer['photo'] ? 'Replace photo...' : 'Choose photo...'; ?></span>
                                    </label>
                                    <div id="photo-preview" class="image-preview"></div>
                                </div>
                                <small class="form-text">JPG, PNG, GIF (max 5MB)</small>
                            </div>
                            <div class="form-group">
                                <label for="id_image">ID Card Image</label>
                                <?php if ($buyer['id_image']): ?>
                                <div class="current-file">
                                    <img src="<?php echo SITE_URL; ?>/uploads/buyers/<?php echo htmlspecialchars($buyer['id_image']); ?>" alt="Current ID">
                                    <label class="delete-checkbox">
                                        <input type="checkbox" name="delete_id_image" value="1"> Remove
                                    </label>
                                </div>
                                <?php endif; ?>
                                <div class="file-upload-wrapper">
                                    <input type="file" name="id_image" id="id_image" class="file-input" accept="image/*" onchange="previewImage(this, 'id-image-preview')">
                                    <label for="id_image" class="file-label">
                                        <i class="fas fa-id-card"></i>
                                        <span><?php echo $buyer['id_image'] ? 'Replace ID image...' : 'Choose ID image...'; ?></span>
                                    </label>
                                    <div id="id-image-preview" class="image-preview"></div>
                                </div>
                                <small class="form-text">Photo of ID card (max 5MB)</small>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="id_document">Scanned ID Document (PDF)</label>
                            <?php if ($buyer['id_document']): ?>
                            <div class="current-file pdf-file">
                                <i class="fas fa-file-pdf"></i>
                                <a href="<?php echo SITE_URL; ?>/uploads/buyers/<?php echo htmlspecialchars($buyer['id_document']); ?>" target="_blank">
                                    View Current PDF
                                </a>
                                <label class="delete-checkbox">
                                    <input type="checkbox" name="delete_id_document" value="1"> Remove
                                </label>
                            </div>
                            <?php endif; ?>
                            <div class="file-upload-wrapper">
                                <input type="file" name="id_document" id="id_document" class="file-input" accept=".pdf" onchange="showFileName(this, 'doc-filename')">
                                <label for="id_document" class="file-label">
                                    <i class="fas fa-file-pdf"></i>
                                    <span id="doc-filename"><?php echo $buyer['id_document'] ? 'Replace PDF...' : 'Choose PDF file...'; ?></span>
                                </label>
                            </div>
                            <small class="form-text">Scanned ID documents (PDF only, max 5MB)</small>
                        </div>
                    </div>

                    <div class="card-footer">
                        <a href="view.php?id=<?php echo $buyerId; ?>" class="btn btn-outline">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .form-container { max-width: 600px; }

        .alert { padding: 1rem 1.5rem; border-radius: 10px; margin-bottom: 1.5rem; display: flex; gap: 0.75rem; }
        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }
        .alert ul { margin: 0; padding-left: 1rem; }

        .card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { padding: 1.25rem 1.5rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; }
        .card-header h3 { margin: 0; font-size: 1rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }
        .card-body { padding: 1.5rem; }
        .card-footer { padding: 1rem 1.5rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: flex-end; gap: 1rem; }

        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .form-group { margin-bottom: 1.25rem; }
        .form-group:last-child { margin-bottom: 0; }
        .form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #374151; font-size: 0.875rem; }
        .form-control { width: 100%; padding: 0.75rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.9rem; transition: all 0.2s; box-sizing: border-box; }
        .form-control:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        textarea.form-control { resize: vertical; min-height: 70px; }

        .file-upload-wrapper { position: relative; }
        .file-input { position: absolute; width: 100%; height: 100%; top: 0; left: 0; opacity: 0; cursor: pointer; z-index: 2; }
        .file-label { display: flex; align-items: center; gap: 0.75rem; padding: 1rem; border: 2px dashed #e2e8f0; border-radius: 8px; cursor: pointer; transition: all 0.2s; background: #f8fafc; }
        .file-label:hover { border-color: #667eea; background: #f0f4ff; }
        .file-label i { font-size: 1.25rem; color: #667eea; }
        .file-label span { color: #64748b; font-size: 0.875rem; }

        .image-preview { margin-top: 0.75rem; }
        .image-preview img { max-width: 120px; max-height: 120px; border-radius: 8px; border: 2px solid #e2e8f0; object-fit: cover; }

        .current-file { display: flex; align-items: center; gap: 0.75rem; padding: 0.75rem; background: #f0fdf4; border: 1px solid #86efac; border-radius: 8px; margin-bottom: 0.75rem; }
        .current-file img { width: 60px; height: 60px; object-fit: cover; border-radius: 6px; border: 1px solid #e2e8f0; }
        .current-file.pdf-file { background: #fef3c7; border-color: #fcd34d; }
        .current-file.pdf-file i { font-size: 1.5rem; color: #dc2626; }
        .current-file a { color: #667eea; text-decoration: none; font-weight: 500; }
        .current-file a:hover { text-decoration: underline; }
        .delete-checkbox { margin-left: auto; display: flex; align-items: center; gap: 0.25rem; font-size: 0.8rem; color: #dc2626; cursor: pointer; }
        .delete-checkbox input { cursor: pointer; }

        .form-text { font-size: 0.75rem; color: #94a3b8; margin-top: 0.25rem; display: block; }

        @media (max-width: 576px) {
            .form-row { grid-template-columns: 1fr; }
            .card-footer { flex-direction: column-reverse; }
            .card-footer .btn { width: 100%; justify-content: center; }
        }
    </style>

    <script>
    function previewImage(input, previewId) {
        const preview = document.getElementById(previewId);
        const label = input.nextElementSibling.querySelector('span');

        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.innerHTML = '<img src="' + e.target.result + '" alt="Preview">';
            };
            reader.readAsDataURL(input.files[0]);
            label.textContent = input.files[0].name;
        }
    }

    function showFileName(input, spanId) {
        const span = document.getElementById(spanId);
        if (input.files && input.files[0]) {
            span.textContent = input.files[0].name;
        }
    }
    </script>
</body>
</html>
