<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}
include '../includes/db.php';

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$company_name = '';
$description = '';
$industry = '';
$website_url = '';
$logo_url = '';
$status = 'active';
$display_order = 0;

if ($id > 0) {
    $stmt = $conn->prepare("SELECT * FROM customers WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        $company_name = $row['company_name'];
        $description = $row['description'];
        $industry = $row['industry'];
        $website_url = $row['website_url'];
        $logo_url = $row['logo_url'];
        $status = $row['status'];
        $display_order = $row['display_order'];
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $company_name = $conn->real_escape_string($_POST['company_name']);
    $description = $conn->real_escape_string($_POST['description']);
    $industry = $conn->real_escape_string($_POST['industry']);
    $website_url = $conn->real_escape_string($_POST['website_url']);
    $status = $conn->real_escape_string($_POST['status']);
    $display_order = intval($_POST['display_order']);
    
    // File upload logic for logo
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
        $target_dir = "../uploads/customers/";
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        
        $file_name = time() . '_' . basename($_FILES["logo"]["name"]);
        $target_file = $target_dir . $file_name;
        
        // Ensure safe upload
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        $valid_extensions = array("jpg","jpeg","png","gif","webp");
        
        if (in_array($imageFileType, $valid_extensions)) {
            if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
                $logo_url = "uploads/customers/" . $file_name;
            }
        }
    }
    
    // Check if user provided an image URL directly instead of uploading
    if (empty($_FILES['logo']['name']) && !empty($_POST['logo_url_direct'])) {
        $logo_url = $conn->real_escape_string($_POST['logo_url_direct']);
    }

    if ($id > 0) {
        $stmt = $conn->prepare("UPDATE customers SET company_name=?, description=?, industry=?, website_url=?, logo_url=?, status=?, display_order=? WHERE id=?");
        $stmt->bind_param("ssssssii", $company_name, $description, $industry, $website_url, $logo_url, $status, $display_order, $id);
    } else {
        $stmt = $conn->prepare("INSERT INTO customers (company_name, description, industry, website_url, logo_url, status, display_order) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssssi", $company_name, $description, $industry, $website_url, $logo_url, $status, $display_order);
    }
    
    if ($stmt->execute()) {
        header("Location: manage_customers.php");
        exit;
    } else {
        $error = "Error saving customer: " . $conn->error;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo $id > 0 ? 'Edit' : 'Add'; ?> Customer</title>
    <link rel="shortcut icon" href="/bm/BM LOGO.jpg" type="image/jpeg">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="dashboard.css">
</head>
<body>
    <div class="sidebar d-flex flex-column flex-shrink-0 p-3 text-white" style="width: 280px;">
        <a href="dashboard.php" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
            <span class="fs-4">Admin Panel</span>
        </a>
        <hr>
        <ul class="nav nav-pills flex-column mb-auto">
            <li class="nav-item">
                <a href="dashboard.php"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a>
            </li>
            <li>
                <a href="manage_services.php"><i class="fas fa-tools me-2"></i> Manage Services</a>
            </li>
            <li>
                <a href="manage_customers.php" class="active"><i class="fas fa-users me-2"></i> Manage Customers</a>
            </li>
            <li>
                <a href="manage_pages.php"><i class="fas fa-file-alt me-2"></i> Manage Content</a>
            </li>
        </ul>
    </div>

    <div class="content">
        <h2><?php echo $id > 0 ? 'Edit' : 'Add'; ?> Customer</h2>
        <a href="manage_customers.php" class="btn btn-secondary mb-3"><i class="fas fa-arrow-left"></i> Back to Customers</a>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>

        <div class="card p-4">
            <form action="" method="POST" enctype="multipart/form-data">
                <div class="mb-3">
                    <label>Company Name *</label>
                    <input type="text" name="company_name" class="form-control" value="<?php echo htmlspecialchars($company_name); ?>" required>
                </div>
                
                <div class="mb-3">
                    <label>Industry / Category</label>
                    <input type="text" name="industry" class="form-control" value="<?php echo htmlspecialchars($industry); ?>" placeholder="e.g. Technology, Construction, Retail">
                </div>
                
                <div class="mb-3">
                    <label>Short Description</label>
                    <textarea name="description" class="form-control" rows="3"><?php echo htmlspecialchars($description); ?></textarea>
                </div>
                
                <div class="mb-3">
                    <label>Website URL (Optional)</label>
                    <input type="url" name="website_url" class="form-control" value="<?php echo htmlspecialchars($website_url); ?>" placeholder="https://example.com">
                </div>

                <div class="mb-3 border p-3 bg-light">
                    <label class="fw-bold">Company Logo</label>
                    
                    <?php if($logo_url): ?>
                        <div class="mb-2">
                            <p class="mb-1 text-muted">Current Logo:</p>
                            <img src="../<?php echo $logo_url; ?>" alt="Current Logo" width="100" style="background:#fff; border:1px solid #ddd; padding:5px;">
                        </div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label text-muted small">Upload Image</label>
                            <input type="file" name="logo" class="form-control" accept="image/*">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-muted small">OR Image URL (if not uploading)</label>
                            <input type="text" name="logo_url_direct" class="form-control" value="<?php echo $logo_url && !str_starts_with($logo_url, 'uploads/') ? htmlspecialchars($logo_url) : ''; ?>" placeholder="images/logo.png">
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Status</label>
                        <select name="status" class="form-control">
                            <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Active (Visible)</option>
                            <option value="inactive" <?php echo $status == 'inactive' ? 'selected' : ''; ?>>Inactive (Hidden)</option>
                        </select>
                    </div>
                    
                    <div class="col-md-6 mb-3">
                        <label>Display Order (0 is first)</label>
                        <input type="number" name="display_order" class="form-control" value="<?php echo $display_order; ?>" min="0">
                    </div>
                </div>

                <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> Save Customer</button>
            </form>
        </div>
    </div>
</body>
</html>
