#include "esp_camera.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include "esp_http_server.h"

const char* ssid     = "Fridho";
const char* password = "123456789.";
String serverURL     = "http://10.10.1.112:5000/upload";

#define PWDN_GPIO_NUM  32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM   0
#define SIOD_GPIO_NUM  26
#define SIOC_GPIO_NUM  27
#define Y9_GPIO_NUM    35
#define Y8_GPIO_NUM    34
#define Y7_GPIO_NUM    39
#define Y6_GPIO_NUM    36
#define Y5_GPIO_NUM    21
#define Y4_GPIO_NUM    19
#define Y3_GPIO_NUM    18
#define Y2_GPIO_NUM     5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM  23
#define PCLK_GPIO_NUM  22

// ================= FLAG =================
volatile bool doCapture = false;

// ================= INIT KAMERA =================
void startCam() {
  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer   = LEDC_TIMER_0;
  config.pin_d0       = Y2_GPIO_NUM;
  config.pin_d1       = Y3_GPIO_NUM;
  config.pin_d2       = Y4_GPIO_NUM;
  config.pin_d3       = Y5_GPIO_NUM;
  config.pin_d4       = Y6_GPIO_NUM;
  config.pin_d5       = Y7_GPIO_NUM;
  config.pin_d6       = Y8_GPIO_NUM;
  config.pin_d7       = Y9_GPIO_NUM;
  config.pin_xclk     = XCLK_GPIO_NUM;
  config.pin_pclk     = PCLK_GPIO_NUM;
  config.pin_vsync    = VSYNC_GPIO_NUM;
  config.pin_href     = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn     = PWDN_GPIO_NUM;
  config.pin_reset    = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  config.frame_size   = FRAMESIZE_VGA;
  config.jpeg_quality = 12;
  config.fb_count     = 1;

  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("[CAM] Init error: 0x%x\n", err);
    return;
  }
  Serial.println("[CAM] Kamera siap.");
}

// ================= UPLOAD KE SERVER =================
void kirimGambar() {
  camera_fb_t* fb = esp_camera_fb_get();
  if (!fb) {
    Serial.println("[CAM] Gagal ambil frame");
    return;
  }

  Serial.printf("[CAM] Frame: %u bytes, uploading...\n", fb->len);

  HTTPClient http;
  http.begin(serverURL);
  http.addHeader("Content-Type", "application/octet-stream");
  http.setTimeout(15000);

  int code = http.POST(fb->buf, fb->len);
  Serial.print("[CAM] Upload HTTP code: "); Serial.println(code);
  if (code > 0) {
    Serial.println("[CAM] Response: " + http.getString());
  } else {
    Serial.print("[CAM] Upload error: "); Serial.println(http.errorToString(code));
  }
  http.end();

  esp_camera_fb_return(fb);
  Serial.println("[CAM] Upload selesai.");
}

// ================= HTTP SERVER HANDLER =================
esp_err_t capture_handler(httpd_req_t* req) {
  Serial.println("[CAM] /capture dipanggil!");
  doCapture = true;
  const char* resp = "{\"status\":\"triggered\"}";
  httpd_resp_set_type(req, "application/json");
  httpd_resp_send(req, resp, strlen(resp));
  return ESP_OK;
}

esp_err_t ping_handler(httpd_req_t* req) {
  const char* resp = "{\"status\":\"ok\"}";
  httpd_resp_set_type(req, "application/json");
  httpd_resp_send(req, resp, strlen(resp));
  return ESP_OK;
}

void startWebServer() {
  httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  config.server_port = 80;

  httpd_handle_t server = NULL;
  if (httpd_start(&server, &config) == ESP_OK) {
    httpd_uri_t capture_uri = {
      .uri      = "/capture",
      .method   = HTTP_GET,
      .handler  = capture_handler,
      .user_ctx = NULL
    };
    httpd_register_uri_handler(server, &capture_uri);

    httpd_uri_t ping_uri = {
      .uri      = "/",
      .method   = HTTP_GET,
      .handler  = ping_handler,
      .user_ctx = NULL
    };
    httpd_register_uri_handler(server, &ping_uri);

    Serial.println("[CAM] Web server jalan di port 80");
    Serial.println("[CAM] IP: " + WiFi.localIP().toString());
  } else {
    Serial.println("[CAM] Gagal start web server");
  }
}

// =====================================================
// ================= SETUP =============================
// =====================================================

void setup() {
  Serial.begin(115200);
  
  WiFi.begin(ssid, password);
  Serial.print("[CAM] Connecting WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\n[CAM] WiFi Connected!");
  Serial.println("[CAM] IP: " + WiFi.localIP().toString());

  startCam();
  startWebServer();
}

// =====================================================
// ================= LOOP ==============================
// =====================================================

void loop() {
  if (doCapture) {
    doCapture = false;
    Serial.println("[CAM] Mengambil gambar...");
    delay(300);
    kirimGambar();
  }
  delay(10);
}
