<?php
/**
 * CMS - Contact Information Management
 * Centralized management for all contact info across the website
 */

require_once '../config/config.php';
requireLogin();
requireAdmin();

$pageTitle = 'Contact Information Management';
$success = '';
$error = '';

$db = getDB();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    try {
        // Update or insert contact information
        $contactData = [
            'company_name' => sanitize($_POST['company_name'] ?? ''),
            'tagline' => sanitize($_POST['tagline'] ?? ''),
            'email_primary' => sanitize($_POST['email_primary'] ?? ''),
            'email_support' => sanitize($_POST['email_support'] ?? ''),
            'phone_primary' => sanitize($_POST['phone_primary'] ?? ''),
            'phone_secondary' => sanitize($_POST['phone_secondary'] ?? ''),
            'address_line1' => sanitize($_POST['address_line1'] ?? ''),
            'address_line2' => sanitize($_POST['address_line2'] ?? ''),
            'city' => sanitize($_POST['city'] ?? ''),
            'state' => sanitize($_POST['state'] ?? ''),
            'country' => sanitize($_POST['country'] ?? ''),
            'postal_code' => sanitize($_POST['postal_code'] ?? ''),
            'working_hours' => sanitize($_POST['working_hours'] ?? ''),
            'map_latitude' => sanitize($_POST['map_latitude'] ?? ''),
            'map_longitude' => sanitize($_POST['map_longitude'] ?? '')
        ];

        foreach ($contactData as $key => $value) {
            $stmt = $db->prepare("
                INSERT INTO settings (key_name, value, category) 
                VALUES (?, ?, 'contact')
                ON DUPLICATE KEY UPDATE value = ?
            ");
            $stmt->execute([$key, $value, $value]);
        }

        // Also update site_name in branding category for consistency
        $siteName = $contactData['company_name'];
        if (!empty($siteName)) {
            $stmt = $db->prepare("
                INSERT INTO settings (key_name, value, category)
                VALUES ('site_name', ?, 'branding')
                ON DUPLICATE KEY UPDATE value = ?
            ");
            $stmt->execute([$siteName, $siteName]);
        }

        // Update social media links
        $socialMedia = [
            'facebook' => sanitize($_POST['facebook'] ?? ''),
            'twitter' => sanitize($_POST['twitter'] ?? ''),
            'linkedin' => sanitize($_POST['linkedin'] ?? ''),
            'instagram' => sanitize($_POST['instagram'] ?? ''),
            'youtube' => sanitize($_POST['youtube'] ?? ''),
            'researchgate' => sanitize($_POST['researchgate'] ?? ''),
            'orcid' => sanitize($_POST['orcid'] ?? '')
        ];

        foreach ($socialMedia as $key => $value) {
            $stmt = $db->prepare("
                INSERT INTO settings (key_name, value, category) 
                VALUES (?, ?, 'social_media')
                ON DUPLICATE KEY UPDATE value = ?
            ");
            $stmt->execute([$key, $value, $value]);
        }

        logActivity('cms_contact_updated', 'settings', null, null, $contactData);
        $success = 'Contact information updated successfully!';

    } catch (Exception $e) {
        error_log("CMS Contact update error: " . $e->getMessage());
        $error = 'Failed to update contact information.';
    }
}

// Fetch current contact information
$contactInfo = [];
$stmt = $db->prepare("SELECT key_name, value FROM settings WHERE category = 'contact'");
$stmt->execute();
while ($row = $stmt->fetch()) {
    $contactInfo[$row['key_name']] = $row['value'];
}

// Fetch social media links
$socialMedia = [];
$stmt = $db->prepare("SELECT key_name, value FROM settings WHERE category = 'social_media'");
$stmt->execute();
while ($row = $stmt->fetch()) {
    $socialMedia[$row['key_name']] = $row['value'];
}

include '../templates/admin-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <div class="col-md-3 col-lg-2 px-0">
            <?php include 'sidebar-new.php'; ?>
        </div>
        
        <!-- Main Content -->
        <div class="col-md-9 col-lg-10">
            <?php include 'header-bar.php'; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="fas fa-check-circle"></i> <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-circle"></i> <?php echo e($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i> <strong>Centralized Management:</strong> 
                All contact information entered here will be automatically displayed across the entire website 
                (footer, contact page, about page, etc.). Update once, reflect everywhere!
            </div>
            
            <form method="POST" class="needs-validation" novalidate>
                <?php echo csrfField(); ?>
                
                <!-- Company Information -->
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-building"></i> Company Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Company/Organization Name *</label>
                                <input type="text" class="form-control" name="company_name" 
                                       value="<?php echo e($contactInfo['company_name'] ?? SITE_NAME); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Tagline/Slogan</label>
                                <input type="text" class="form-control" name="tagline" 
                                       value="<?php echo e($contactInfo['tagline'] ?? ''); ?>" 
                                       placeholder="Your company tagline">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Contact Details -->
                <div class="card mb-4">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="fas fa-envelope"></i> Contact Details</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Primary Email *</label>
                                <input type="email" class="form-control" name="email_primary" 
                                       value="<?php echo e($contactInfo['email_primary'] ?? SITE_EMAIL); ?>" required>
                                <small class="text-muted">Main contact email</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Support Email</label>
                                <input type="email" class="form-control" name="email_support" 
                                       value="<?php echo e($contactInfo['email_support'] ?? ''); ?>" 
                                       placeholder="support@example.com">
                                <small class="text-muted">For support inquiries</small>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Primary Phone</label>
                                <input type="tel" class="form-control" name="phone_primary" 
                                       value="<?php echo e($contactInfo['phone_primary'] ?? ''); ?>" 
                                       placeholder="+1 (555) 123-4567">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Secondary Phone</label>
                                <input type="tel" class="form-control" name="phone_secondary" 
                                       value="<?php echo e($contactInfo['phone_secondary'] ?? ''); ?>" 
                                       placeholder="+1 (555) 987-6543">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Physical Address -->
                <div class="card mb-4">
                    <div class="card-header bg-info text-white">
                        <h5 class="mb-0"><i class="fas fa-map-marker-alt"></i> Physical Address</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Address Line 1</label>
                            <input type="text" class="form-control" name="address_line1" 
                                   value="<?php echo e($contactInfo['address_line1'] ?? ''); ?>" 
                                   placeholder="Street address">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Address Line 2</label>
                            <input type="text" class="form-control" name="address_line2" 
                                   value="<?php echo e($contactInfo['address_line2'] ?? ''); ?>" 
                                   placeholder="Apartment, suite, unit, etc.">
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">City</label>
                                <input type="text" class="form-control" name="city" 
                                       value="<?php echo e($contactInfo['city'] ?? ''); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">State/Province</label>
                                <input type="text" class="form-control" name="state" 
                                       value="<?php echo e($contactInfo['state'] ?? ''); ?>">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Country</label>
                                <input type="text" class="form-control" name="country" 
                                       value="<?php echo e($contactInfo['country'] ?? ''); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Postal/ZIP Code</label>
                                <input type="text" class="form-control" name="postal_code" 
                                       value="<?php echo e($contactInfo['postal_code'] ?? ''); ?>">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Working Hours & Map -->
                <div class="card mb-4">
                    <div class="card-header bg-warning text-dark">
                        <h5 class="mb-0"><i class="fas fa-clock"></i> Working Hours & Location</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Working Hours</label>
                            <textarea class="form-control" name="working_hours" rows="3" 
                                      placeholder="Monday - Friday: 9:00 AM - 5:00 PM&#10;Saturday: 10:00 AM - 2:00 PM&#10;Sunday: Closed"><?php echo e($contactInfo['working_hours'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Map Latitude</label>
                                <input type="text" class="form-control" name="map_latitude" 
                                       value="<?php echo e($contactInfo['map_latitude'] ?? ''); ?>" 
                                       placeholder="40.7128">
                                <small class="text-muted">For Google Maps integration</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Map Longitude</label>
                                <input type="text" class="form-control" name="map_longitude" 
                                       value="<?php echo e($contactInfo['map_longitude'] ?? ''); ?>" 
                                       placeholder="-74.0060">
                                <small class="text-muted">For Google Maps integration</small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Social Media Links -->
                <div class="card mb-4">
                    <div class="card-header bg-dark text-white">
                        <h5 class="mb-0"><i class="fas fa-share-alt"></i> Social Media Links</h5>
                    </div>
                    <div class="card-body">
                        <p class="text-muted">Enter full URLs for your social media profiles. Leave blank to hide.</p>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fab fa-facebook text-primary"></i> Facebook</label>
                                <input type="url" class="form-control" name="facebook" 
                                       value="<?php echo e($socialMedia['facebook'] ?? ''); ?>" 
                                       placeholder="https://facebook.com/yourpage">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fab fa-twitter text-info"></i> Twitter</label>
                                <input type="url" class="form-control" name="twitter" 
                                       value="<?php echo e($socialMedia['twitter'] ?? ''); ?>" 
                                       placeholder="https://twitter.com/yourhandle">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fab fa-linkedin text-primary"></i> LinkedIn</label>
                                <input type="url" class="form-control" name="linkedin" 
                                       value="<?php echo e($socialMedia['linkedin'] ?? ''); ?>" 
                                       placeholder="https://linkedin.com/company/yourcompany">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fab fa-instagram text-danger"></i> Instagram</label>
                                <input type="url" class="form-control" name="instagram" 
                                       value="<?php echo e($socialMedia['instagram'] ?? ''); ?>" 
                                       placeholder="https://instagram.com/yourprofile">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fab fa-youtube text-danger"></i> YouTube</label>
                                <input type="url" class="form-control" name="youtube" 
                                       value="<?php echo e($socialMedia['youtube'] ?? ''); ?>" 
                                       placeholder="https://youtube.com/c/yourchannel">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fab fa-researchgate text-success"></i> ResearchGate</label>
                                <input type="url" class="form-control" name="researchgate" 
                                       value="<?php echo e($socialMedia['researchgate'] ?? ''); ?>" 
                                       placeholder="https://researchgate.net/profile/yourprofile">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fab fa-orcid text-success"></i> ORCID</label>
                                <input type="url" class="form-control" name="orcid" 
                                       value="<?php echo e($socialMedia['orcid'] ?? ''); ?>" 
                                       placeholder="https://orcid.org/0000-0000-0000-0000">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-between">
                    <a href="dashboard.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to Dashboard
                    </a>
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="fas fa-save"></i> Save Contact Information
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include '../templates/admin-footer.php'; ?>
