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

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $company_name = trim($_POST['company_name'] ?? '');
    $legal_name = trim($_POST['legal_name'] ?? '');
    $short_name = trim($_POST['short_name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $about_company = trim($_POST['about_company'] ?? '');
    $industry = trim($_POST['industry'] ?? '');
    $company_type = trim($_POST['company_type'] ?? '');
    $year_established = trim($_POST['year_established'] ?? '');
    $registration_no = trim($_POST['registration_no'] ?? '');
    $cin = trim($_POST['cin'] ?? '');
    $gst_no = trim($_POST['gst_no'] ?? '');
    $pan = trim($_POST['pan'] ?? '');
    $tan = trim($_POST['tan'] ?? '');
    $website_url = trim($_POST['website_url'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    
    $address = trim($_POST['address'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $state = trim($_POST['state'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $pincode = trim($_POST['pincode'] ?? '');
    
    $business_details = trim($_POST['business_details'] ?? '');
    $services = trim($_POST['services'] ?? '');
    $products = trim($_POST['products'] ?? '');
    $experience = trim($_POST['experience'] ?? '');
    $employees = trim($_POST['employees'] ?? '');
    $projects_completed = trim($_POST['projects_completed'] ?? '');
    $turnover = trim($_POST['turnover'] ?? '');
    $certifications = trim($_POST['certifications'] ?? '');
    $awards = trim($_POST['awards'] ?? '');
    
    $display_order = intval($_POST['display_order'] ?? 0);
    $status = in_array($_POST['status'] ?? '', ['Published', 'Draft', 'Inactive']) ? $_POST['status'] : 'Published';
    
    if (empty($company_name)) {
        $error = "Company Name is required.";
    } else {
        $logo_path = '';
        $banner_path = '';
        
        $target_dir = "../uploads/companies/";
        if (!is_dir($target_dir)) {
            @mkdir($target_dir, 0777, true);
        }
        
        $allowed_ext = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        
        // Handle Logo Upload
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, $allowed_ext)) {
                $unique_name = 'logo_' . uniqid() . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['logo']['tmp_name'], $target_dir . $unique_name)) {
                    $logo_path = 'uploads/companies/' . $unique_name;
                }
            } else {
                $error = "Invalid logo image format. Allowed: JPG, PNG, WEBP, GIF.";
            }
        } elseif (!empty($_POST['logo_url'])) {
            $logo_path = trim($_POST['logo_url']);
        }
        
        // Handle Banner Upload
        if (isset($_FILES['banner']) && $_FILES['banner']['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES['banner']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, $allowed_ext)) {
                $unique_banner = 'banner_' . uniqid() . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['banner']['tmp_name'], $target_dir . $unique_banner)) {
                    $banner_path = 'uploads/companies/' . $unique_banner;
                }
            } else {
                $error = "Invalid banner image format. Allowed: JPG, PNG, WEBP, GIF.";
            }
        } elseif (!empty($_POST['banner_url'])) {
            $banner_path = trim($_POST['banner_url']);
        }
        
        if (empty($error)) {
            $stmt = $conn->prepare("INSERT INTO companies (
                company_name, legal_name, short_name, logo, banner, description, about_company,
                industry, company_type, year_established, registration_no, cin, gst_no, pan, tan,
                website_url, email, phone, address, city, state, country, pincode,
                business_details, services, products, experience, employees, projects_completed,
                turnover, certifications, awards, display_order, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            $stmt->bind_param(
                "ssssssssssssssssssssssssssssssssis",
                $company_name, $legal_name, $short_name, $logo_path, $banner_path, $description, $about_company,
                $industry, $company_type, $year_established, $registration_no, $cin, $gst_no, $pan, $tan,
                $website_url, $email, $phone, $address, $city, $state, $country, $pincode,
                $business_details, $services, $products, $experience, $employees, $projects_completed,
                $turnover, $certifications, $awards, $display_order, $status
            );
            
            if ($stmt->execute()) {
                $new_id = $stmt->insert_id;
                header("Location: manage_customers.php?msg=added");
                exit;
            } else {
                $error = "Database Error: " . $conn->error;
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Company Profile - Admin</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">
    <style>
        .form-section {
            background: #fff;
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.06);
        }
        .form-section-title {
            font-size: 16px;
            font-weight: 700;
            color: #1e293b;
            border-bottom: 2px solid #f1f5f9;
            padding-bottom: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .preview-box {
            width: 100px;
            height: 100px;
            border: 2px dashed #cbd5e1;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            background: #f8fafc;
            margin-top: 10px;
        }
        .preview-box img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        .banner-preview-box {
            width: 100%;
            height: 120px;
            border: 2px dashed #cbd5e1;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            background: #f8fafc;
            margin-top: 10px;
        }
        .banner-preview-box img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
</head>
<body>
    <div class="sidebar d-flex flex-column flex-shrink-0 p-3 text-white">
        <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 fw-bold">Admin Panel</span>
        </a>
        <hr>
        <ul class="nav nav-pills flex-column mb-auto">
            <li><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-building me-2"></i> Manage Companies</a></li>
            <li><a href="manage_founders.php"><i class="fas fa-user-tie me-2"></i> Manage Founders</a></li>
            <li><a href="manage_directors.php"><i class="fas fa-users-cog me-2"></i> Manage Directors</a></li>
            <li><a href="manage_pages.php"><i class="fas fa-file-alt me-2"></i> Manage Content</a></li>
            <li><a href="manage_blogs.php"><i class="fas fa-blog me-2"></i> Manage Blogs</a></li>
            <li><a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt me-2"></i> Logout</a></li>
        </ul>
    </div>

    <div class="content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="mb-0 fw-bold"><i class="fas fa-plus-circle text-primary me-2"></i> Add New Company</h2>
                <small class="text-muted">Create a complete company profile with registration, business and contact info</small>
            </div>
            <a href="manage_customers.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back to Companies</a>
        </div>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i> <?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <form action="company_add.php" method="POST" enctype="multipart/form-data">
            <!-- 1. Basic Company Information -->
            <div class="form-section">
                <div class="form-section-title"><i class="fas fa-info-circle text-primary"></i> 1. Basic Company Information</div>
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label fw-bold">Company Name <span class="text-danger">*</span></label>
                        <input type="text" name="company_name" class="form-control" required placeholder="e.g. BALIMEEN PRIVATE LIMITED" value="<?php echo htmlspecialchars($_POST['company_name'] ?? ''); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-bold">Legal Company Name</label>
                        <input type="text" name="legal_name" class="form-control" placeholder="e.g. Balimeen Private Limited" value="<?php echo htmlspecialchars($_POST['legal_name'] ?? ''); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-bold">Short / Brand Name</label>
                        <input type="text" name="short_name" class="form-control" placeholder="e.g. BALIMEEN" value="<?php echo htmlspecialchars($_POST['short_name'] ?? ''); ?>">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label fw-bold">Company Type</label>
                        <select name="company_type" class="form-select">
                            <option value="Private Limited">Private Limited (Pvt Ltd)</option>
                            <option value="Public Limited">Public Limited (Ltd)</option>
                            <option value="LLP">Limited Liability Partnership (LLP)</option>
                            <option value="Partnership">Partnership Firm</option>
                            <option value="Proprietorship">Sole Proprietorship</option>
                            <option value="Government / PSU">Government / PSU Undertaking</option>
                            <option value="Joint Venture">Joint Venture</option>
                            <option value="Startup / Enterprise">Startup / Enterprise</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold">Industry / Category</label>
                        <input type="text" name="industry" class="form-control" placeholder="e.g. Construction & Engineering" value="<?php echo htmlspecialchars($_POST['industry'] ?? ''); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold">Year Established</label>
                        <input type="text" name="year_established" class="form-control" placeholder="e.g. 2018" value="<?php echo htmlspecialchars($_POST['year_established'] ?? ''); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold">Website URL</label>
                        <input type="url" name="website_url" class="form-control" placeholder="https://example.com" value="<?php echo htmlspecialchars($_POST['website_url'] ?? ''); ?>">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label fw-bold">Official Email</label>
                        <input type="email" name="email" class="form-control" placeholder="info@balimeen.com" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">Contact Number / Phone</label>
                        <input type="text" name="phone" class="form-control" placeholder="+91 9876543210" value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label fw-bold">Company Logo</label>
                        <input type="file" name="logo" class="form-control" accept="image/*" onchange="previewImage(this, 'logoPreview')">
                        <input type="text" name="logo_url" class="form-control form-control-sm mt-1" placeholder="Or enter existing path / image URL">
                        <div class="preview-box" id="logoPreviewBox">
                            <img id="logoPreview" src="" style="display:none;" alt="Logo Preview">
                            <span id="logoPlaceholder" class="text-muted small">Logo Preview</span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">Company Banner Image</label>
                        <input type="file" name="banner" class="form-control" accept="image/*" onchange="previewImage(this, 'bannerPreview')">
                        <input type="text" name="banner_url" class="form-control form-control-sm mt-1" placeholder="Or enter existing path / banner URL">
                        <div class="banner-preview-box" id="bannerPreviewBox">
                            <img id="bannerPreview" src="" style="display:none;" alt="Banner Preview">
                            <span id="bannerPlaceholder" class="text-muted small">Banner Preview</span>
                        </div>
                    </div>

                    <div class="col-md-12">
                        <label class="form-label fw-bold">Short Description (Displays on cards & summaries)</label>
                        <textarea name="description" class="form-control" rows="2" placeholder="Brief overview of company and value proposition..."><?php echo htmlspecialchars($_POST['description'] ?? ''); ?></textarea>
                    </div>

                    <div class="col-md-12">
                        <label class="form-label fw-bold">About Company (Full detailed profile / story)</label>
                        <textarea name="about_company" class="form-control" rows="5" placeholder="Comprehensive background, mission, vision, history and corporate values..."><?php echo htmlspecialchars($_POST['about_company'] ?? ''); ?></textarea>
                    </div>
                </div>
            </div>

            <!-- 2. Legal & Registration Details -->
            <div class="form-section">
                <div class="form-section-title"><i class="fas fa-file-contract text-primary"></i> 2. Legal & Registration Details</div>
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">Registration Number</label>
                        <input type="text" name="registration_no" class="form-control" placeholder="e.g. ROC-123456" value="<?php echo htmlspecialchars($_POST['registration_no'] ?? ''); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Corporate Identification Number (CIN)</label>
                        <input type="text" name="cin" class="form-control" placeholder="e.g. U45200DL2021PTC123456" value="<?php echo htmlspecialchars($_POST['cin'] ?? ''); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">GST Number</label>
                        <input type="text" name="gst_no" class="form-control" placeholder="e.g. 07AAAAA0000A1Z5" value="<?php echo htmlspecialchars($_POST['gst_no'] ?? ''); ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">PAN (Permanent Account Number)</label>
                        <input type="text" name="pan" class="form-control" placeholder="e.g. ABCDE1234F" value="<?php echo htmlspecialchars($_POST['pan'] ?? ''); ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">TAN Number</label>
                        <input type="text" name="tan" class="form-control" placeholder="e.g. DELA12345B" value="<?php echo htmlspecialchars($_POST['tan'] ?? ''); ?>">
                    </div>
                </div>
            </div>

            <!-- 3. Registered Office & Address -->
            <div class="form-section">
                <div class="form-section-title"><i class="fas fa-map-marker-alt text-primary"></i> 3. Registered Office & Address</div>
                <div class="row g-3">
                    <div class="col-md-12">
                        <label class="form-label">Office Address / Street</label>
                        <textarea name="address" class="form-control" rows="2" placeholder="Building, Street, Area..."><?php echo htmlspecialchars($_POST['address'] ?? ''); ?></textarea>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">City</label>
                        <input type="text" name="city" class="form-control" placeholder="e.g. New Delhi" value="<?php echo htmlspecialchars($_POST['city'] ?? ''); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">State</label>
                        <input type="text" name="state" class="form-control" placeholder="e.g. Delhi" value="<?php echo htmlspecialchars($_POST['state'] ?? ''); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Country</label>
                        <input type="text" name="country" class="form-control" value="India" value="<?php echo htmlspecialchars($_POST['country'] ?? 'India'); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">PIN Code</label>
                        <input type="text" name="pincode" class="form-control" placeholder="e.g. 110001" value="<?php echo htmlspecialchars($_POST['pincode'] ?? ''); ?>">
                    </div>
                </div>
            </div>

            <!-- 4. Business Information, Capabilities & Highlights -->
            <div class="form-section">
                <div class="form-section-title"><i class="fas fa-briefcase text-primary"></i> 4. Business Details, Services & Stats</div>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Key Services (Comma or line separated)</label>
                        <textarea name="services" class="form-control" rows="3" placeholder="Civil Construction, Petrol Pump Turnkey, Furniture Works..."><?php echo htmlspecialchars($_POST['services'] ?? ''); ?></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Products / Offerings</label>
                        <textarea name="products" class="form-control" rows="3" placeholder="Steel structures, Aluminium fittings, Modular furnishings..."><?php echo htmlspecialchars($_POST['products'] ?? ''); ?></textarea>
                    </div>
                    <div class="col-md-12">
                        <label class="form-label">Main Business Activities & Scope</label>
                        <textarea name="business_details" class="form-control" rows="3" placeholder="Details of business operations, market presence, core expertise..."><?php echo htmlspecialchars($_POST['business_details'] ?? ''); ?></textarea>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Experience (Years)</label>
                        <input type="text" name="experience" class="form-control" placeholder="e.g. 10+ Years" value="<?php echo htmlspecialchars($_POST['experience'] ?? ''); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Number of Employees</label>
                        <input type="text" name="employees" class="form-control" placeholder="e.g. 50+ Professionals" value="<?php echo htmlspecialchars($_POST['employees'] ?? ''); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Projects Completed</label>
                        <input type="text" name="projects_completed" class="form-control" placeholder="e.g. 150+ Projects" value="<?php echo htmlspecialchars($_POST['projects_completed'] ?? ''); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Annual Turnover (Optional)</label>
                        <input type="text" name="turnover" class="form-control" placeholder="e.g. ₹25 Cr+" value="<?php echo htmlspecialchars($_POST['turnover'] ?? ''); ?>">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">Certifications & Accreditations</label>
                        <textarea name="certifications" class="form-control" rows="2" placeholder="e.g. ISO 9001:2015, OHSAS 18001, CPWD Registered..."><?php echo htmlspecialchars($_POST['certifications'] ?? ''); ?></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Awards & Recognitions</label>
                        <textarea name="awards" class="form-control" rows="2" placeholder="e.g. Best Construction Contractor 2023, Quality Excellence Award..."><?php echo htmlspecialchars($_POST['awards'] ?? ''); ?></textarea>
                    </div>
                </div>
            </div>

            <!-- 5. Publishing & Display Settings -->
            <div class="form-section">
                <div class="form-section-title"><i class="fas fa-cog text-primary"></i> 5. Display & Publishing Settings</div>
                <div class="row g-3 align-items-center">
                    <div class="col-md-4">
                        <label class="form-label fw-bold">Publish Status</label>
                        <select name="status" class="form-select">
                            <option value="Published" selected>Published (Visible on Website)</option>
                            <option value="Draft">Draft (Hidden from Public)</option>
                            <option value="Inactive">Inactive (Archived)</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-bold">Display Order</label>
                        <input type="number" name="display_order" class="form-control" value="0" min="0">
                        <small class="text-muted">Lower number displays first (0, 1, 2...)</small>
                    </div>
                    <div class="col-md-4 text-end pt-3">
                        <button type="submit" class="btn btn-primary btn-lg px-4"><i class="fas fa-save me-1"></i> Save Company Profile</button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <script>
        function previewImage(input, targetId) {
            const preview = document.getElementById(targetId);
            const placeholder = document.getElementById(targetId === 'logoPreview' ? 'logoPlaceholder' : 'bannerPlaceholder');
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                    if (placeholder) placeholder.style.display = 'none';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
