#include "esp_camera.h"
#include <WiFi.h>
#include <WiFiClient.h>

// =======================
// WIFI
// =======================
const char* ssid = "P nyoman";
const char* password = "123456789";

// =======================
// SERVER
// =======================
const char* serverHost = "192.168.1.5";
const int serverPort = 80;
const char* serverPath = "/smart-drop-point/public/api/upload_cam.php";

// =======================
// RELAY + LED
// =======================
#define RELAY_PIN 13
#define LED_MERAH 12
#define LED_HIJAU 14

// =======================
// AI THINKER CAMERA PIN
// =======================
#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

// =======================
// CAMERA INIT
// =======================
bool initCamera() {

  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_sccb_sda = SIOD_GPIO_NUM;
  config.pin_sccb_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_QVGA;
  config.jpeg_quality = 15;
  config.fb_count = 1;

  esp_err_t err = esp_camera_init(&config);

  if (err != ESP_OK) {

    Serial.printf("Camera init gagal: 0x%x\n", err);

    return false;
  }

  Serial.println("Camera OK");

  return true;
}

// =======================
// WIFI CONNECT
// =======================
bool connectWiFi() {

  Serial.println("CONNECT WIFI");

  WiFi.begin(ssid, password);

  int retry = 0;

  while (WiFi.status() != WL_CONNECTED && retry < 30) {

    delay(500);
    Serial.print(".");

    retry++;
  }

  Serial.println();

  if (WiFi.status() == WL_CONNECTED) {

    Serial.println("WiFi Connected");
    Serial.println(WiFi.localIP());

    return true;
  }

  Serial.println("WiFi gagal");

  return false;
}

// =======================
// CAPTURE FOTO
// =======================
camera_fb_t* capturePhoto() {

  Serial.println("CAPTURE FOTO");

  camera_fb_t *fb = esp_camera_fb_get();

  if (!fb) {

    Serial.println("Capture gagal");

    return NULL;
  }

  Serial.println("Foto berhasil");

  return fb;
}

// =======================
// UPLOAD FOTO
// =======================
String uploadPhoto(camera_fb_t *fb) {

  Serial.println("UPLOAD FOTO");

  WiFiClient client;

  if (!client.connect(serverHost, serverPort)) {

    Serial.println("Server gagal connect");

    return "CONNECT_FAILED";
  }

  String boundary = "----ESP32CAM";

  String head = "";
  head += "--" + boundary + "\r\n";
  head += "Content-Disposition: form-data; name=\"foto\"; filename=\"capture.jpg\"\r\n";
  head += "Content-Type: image/jpeg\r\n\r\n";

  String tail = "\r\n--" + boundary + "--\r\n";

  uint32_t contentLength =
    head.length() +
    fb->len +
    tail.length();

  client.print(
    String("POST ") +
    serverPath +
    " HTTP/1.1\r\n"
  );

  client.print(
    String("Host: ") +
    serverHost +
    "\r\n"
  );

  client.print("Connection: close\r\n");

  client.print(
    String("Content-Type: multipart/form-data; boundary=") +
    boundary +
    "\r\n"
  );

  client.print(
    String("Content-Length: ") +
    contentLength +
    "\r\n\r\n"
  );

  client.print(head);

  client.write(fb->buf, fb->len);

  client.print(tail);

  String response = "";

  unsigned long timeout = millis();

  while (millis() - timeout < 10000) {

    while (client.available()) {

      char c = client.read();

      response += c;

      timeout = millis();
    }

    if (!client.connected()) {
      break;
    }

    delay(10);
  }

  client.stop();

  Serial.println("RESPONSE:");
  Serial.println(response);

  return response;
}

// =======================
// SETUP
// =======================
void setup() {

  Serial.begin(115200);

  delay(2000);

  // =======================
  // PIN MODE
  // =======================
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(LED_MERAH, OUTPUT);
  pinMode(LED_HIJAU, OUTPUT);

  // =======================
  // AWAL TERKUNCI
  // =======================
  digitalWrite(RELAY_PIN, HIGH);

  digitalWrite(LED_MERAH, LOW);
  digitalWrite(LED_HIJAU, LOW);

  Serial.println("ESP32 START");

  // =======================
  // CAMERA
  // =======================
  if (!initCamera()) {
    return;
  }

  // =======================
  // WIFI
  // =======================
  if (!connectWiFi()) {
    return;
  }

  // =======================
  // FOTO
  // =======================
  camera_fb_t *fb = capturePhoto();

  if (!fb) {
    return;
  }

  // =======================
  // UPLOAD
  // =======================
  String response = uploadPhoto(fb);

  esp_camera_fb_return(fb);

  // =======================
  // CEK VALID
  // =======================
  if (response.indexOf("VALID") >= 0) {

    Serial.println("RESI VALID");

    digitalWrite(LED_HIJAU, HIGH);
    digitalWrite(LED_MERAH, LOW);

    // BUKA SOLENOID
    digitalWrite(RELAY_PIN, LOW);

    delay(5000);

    // KUNCI LAGI
    digitalWrite(RELAY_PIN, HIGH);

    digitalWrite(LED_HIJAU, LOW);

  } else {

    Serial.println("RESI TIDAK VALID");

    digitalWrite(LED_MERAH, HIGH);

    delay(3000);

    digitalWrite(LED_MERAH, LOW);

    digitalWrite(RELAY_PIN, HIGH);
  }

  Serial.println("SELESAI");
}

void loop() {

}