<?php
/**
 * Contact API
 * GET /api/contact.php - Get contact info
 * PUT /api/contact.php - Update contact info (auth required)
 */

require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$db = getDB();

// GET - Get contact info
if ($method === 'GET') {
    $stmt = $db->prepare("SELECT * FROM contact WHERE id = 'main'");
    $stmt->execute();
    $contact = $stmt->fetch();
    
    if (!$contact) {
        // Return default
        jsonResponse([
            'id' => 'main',
            'phone' => '+62 815-5433-3316',
            'email' => 'cs.rhelektronik@gmail.com',
            'address' => 'CV RH Elektronik, Jl. Pasar Gn.Kalong 01/09 Tasikmalaya, Jawa Barat, Indonesia',
            'hours' => 'Senin - Sabtu, 08.00 - 16.00 WIB',
            'map_embed' => ''
        ]);
    }
    
    jsonResponse($contact);
}

// PUT - Update contact info
if ($method === 'PUT') {
    requireAuth();
    $input = getJsonInput();
    
    // Check if contact exists
    $stmt = $db->prepare("SELECT * FROM contact WHERE id = 'main'");
    $stmt->execute();
    $contact = $stmt->fetch();
    
    if ($contact) {
        // Update existing
        $phone = $input['phone'] ?? $contact['phone'];
        $email = $input['email'] ?? $contact['email'];
        $address = $input['address'] ?? $contact['address'];
        $hours = $input['hours'] ?? $contact['hours'];
        $mapEmbed = $input['map_embed'] ?? $contact['map_embed'];
        
        $stmt = $db->prepare("UPDATE contact SET phone = ?, email = ?, address = ?, hours = ?, map_embed = ? WHERE id = 'main'");
        $stmt->execute([$phone, $email, $address, $hours, $mapEmbed]);
    } else {
        // Create new
        $phone = $input['phone'] ?? '';
        $email = $input['email'] ?? '';
        $address = $input['address'] ?? '';
        $hours = $input['hours'] ?? '';
        $mapEmbed = $input['map_embed'] ?? '';
        
        $stmt = $db->prepare("INSERT INTO contact (id, phone, email, address, hours, map_embed) VALUES ('main', ?, ?, ?, ?, ?)");
        $stmt->execute([$phone, $email, $address, $hours, $mapEmbed]);
    }
    
    // Return updated contact
    $stmt = $db->prepare("SELECT * FROM contact WHERE id = 'main'");
    $stmt->execute();
    jsonResponse($stmt->fetch());
}

errorResponse('Method not allowed', 405);
